Question

I'm following along in the book, Everyday Rails Testing with RSpec, and it makes use of assigns:

it "assigns the requested Category to @category" do
  category = FactoryGirl.create(:category)
  binding.pry
  get :edit, id: category
  expect(assigns(:category)).to eq category
end

However, my tests are failing so I'm using pry to dig in (as seen above)

[1] pry(#<RSpec::Core::ExampleGroup::Nested_1::Nested_3::Nested_1>)> category
=> #<Category id: 83, name: "Example  category", user_id: 1, created_at: "2014-03-31 12:25:45", updated_at: "2014-03-31 12:25:45", amount: nil, group_id: nil, amount_in: nil, amount_out: nil>

..ok, category is fine. Great! But, I'm not really sure what assigns actually does and couldn't find documentation on it as I don't really know where it belongs to (RSpec? FactoryGirl?). Here's the result I'm getting anyway:

[2] pry(#<RSpec::Core::ExampleGroup::Nested_1::Nested_3::Nested_1>)> assigns(:category)
=> nil

..and it's nil. Can someone please point me in the right direction here if it's something obvious, and even explain just a little what assigns actually does here (or is meant to do), would be very much appreciated. Also, where is the documentation for assigns?

Was it helpful?

Solution

assigns is actually part of the Rails functional testing framework. It's a way to access the instance variables (the @ variables) that you assign in your controller - so assigns(:category) will be nil if you never set @category in your controller action.

For more information about assigns, check out this section of the Ruby on Rails guide to testing. The full documentation for it is in the ActionController::TestCase documentation.

OTHER TIPS

What you should expect from the assign after calling your controller, is to have the value that the controller sets to the instance variable. You could see it like using @category. So the category created with FactoryGirl is not equals to the one created by your controller (in this case seems your action is returning nil value in your instance variable)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top