Search code examples
ruby-on-railsrspeccontrollerput

Rspec spec for put action not passing


Can anyone see why my put spec for my controller wont pass?

Here is what my update action in my controller looks like:

def update
 @user = User.find(current_user.id)

 respond_to do |format|
   if @user.update_attributes(permitted_update_params)
     format.html { redirect_to new_topup_path, notice: 'Billing address was succesfully updated' }
     format.json { respond_with_bip(@user) }
   else
     format.html { render action: "edit" }
     format.json { render json: @user.errors, status: :unprocessable_entity }
   end
 end
end

And my spec looks like this:

context "given a user who wants to update their billing address" do
 let!(:user) { create(:user, billing_address: "My initial address") }

 before(:each) do
   allow(controller).to receive(:current_user) {:user}
   patch :update, { user: { :billing_address => "My Second address" } }
 end

 it "should update the users billing address" do
   expect(user.billing_address).to eq("My Second address")
 end
end

My spec displays this message:

Failure/Error: expect(user.billing_address).to eq("My Second address")

   expected: "My Second address"
        got: "My initial address"

Solution

  • You likely need to reload the user instance in your test. The database has been updated, but the user instance won't update itself to reflect that.

    expect(user.reload.billing_address).to eq("My Second address")
    

    There are also other problems with your code, like this line:

    allow(controller).to receive(:current_user) {:user}
    

    You've defined a user with let(:user), which means you now have a user variable available to your spec - note user, not :user!