everydayrails / rails-4-1-rspec-3-0

Code samples for Everyday Rails Testing with RSpec, Rails 4.1/RSpec 3.0 edition
272 stars 229 forks source link

Instance variable in PATCH controller specs #53

Open ristovskiv opened 9 years ago

ristovskiv commented 9 years ago

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.

ruralocity commented 9 years ago

I see this question a lot ... I'm going to write a blog post to provide some illustrated details.

ristovskiv commented 9 years ago

Thank you for the response, looking forward for that blog post.

ruralocity commented 9 years ago

I haven't forgotten this ... I haven't been feeling well and have been sleeping when I usually write.

ristovskiv commented 9 years ago

No biggies, thank you really for replying and for putting the work and effort to share your knowledge. Hope you'll get well soon.

ruralocity commented 9 years ago

Here you go, hope it helps! http://everydayrails.com/2015/04/05/rspec-assigns-rails-testing.html

ristovskiv commented 9 years ago

Thank you so much! Great article!