Instance variable in PATCH controller specs
Opened this issue · 6 comments
I need to ask you one quick question and you may find it pretty simple but I just couldn't find the answer for it anywhere.
When I test the controller 'patch' method I run into something that was really intriguing for me.
describe 'PATCH #update' do
before :each do
@contact = create(:contact,
firstname: 'Lawrence',
lastname: 'Smith')
end
context "valid attributes" do
it "locates the requested @contact" do
patch :update, id: @contact, contact: attributes_for(:contact)
expect(assigns(:contact)).to eq(@contact)
end
it "changes @contact's attributes" do
patch :update, id: @contact,
contact: attributes_for(:contact,
firstname: 'Larry',
lastname: 'Smith')
# @contact.reload
p @contact ------------ it prints #<Contact id: 1, firstname: "Lawrence", lastname: "Smith", email: "amya@pfannerstill.org" ...> ???????
p @contact.changes ---- it prints {} (empty hash, no changes)
p assings(:contact) == @contact --- it prints "true"
p @contact.reload ---- it prints #<Contact id: 1, firstname: "Larry", lastname: "Smith", email: "damaris.beier@gloverframi.info" ...>
p @contact == @contact.reload ... it prints "true"
end
end
end
I understand why we should reload, because of persistance, and that @contact needs to be the same as assigns(:contact), but what I don't understand is why if I print the @contact it shows his old values. Plus if I write an example like this "expect(@contact.name).to eq ' Larry Smith' " it fails.
I see this question a lot ... I'm going to write a blog post to provide some illustrated details.
Thank you for the response, looking forward for that blog post.
I haven't forgotten this ... I haven't been feeling well and have been sleeping when I usually write.
No biggies, thank you really for replying and for putting the work and effort to share your knowledge. Hope you'll get well soon.
Here you go, hope it helps! http://everydayrails.com/2015/04/05/rspec-assigns-rails-testing.html
Thank you so much! Great article!