25

Used in automatically generated tests:

test "should create item" do
  login_user
  assert_difference('Item.count') do
    post :create, item: { creator: @item.creator, title: @item.title, user_id: @item.user_id, text: 'Hello, world!' }
  end

  assert_redirected_to(assigns(:item))
end

Rails documentation doesn't have any description. What's the purpose of this method and how to use it?

ndnenkov
  • 35,425
  • 9
  • 72
  • 104
Dan
  • 1,274
  • 2
  • 15
  • 32

2 Answers2

33

It means if a controller defined an instance variable @item="something".

You can fetch an instance variable in your test with e.g.:

# It will check if the instance variable is a string.
assert_kind_of String, assigns(:item)
Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59
Anil Maurya
  • 2,298
  • 1
  • 22
  • 28
6

Be aware assigns deprecated in Rails 5. And extracted to separate gem. To use it you must include 'rails-controller-testing' to your gemfile.

Kevin Ghadyani
  • 6,829
  • 6
  • 44
  • 62
woto
  • 2,893
  • 1
  • 29
  • 24
  • 2
    Wanted to clarify since I was curious, found the article, and it does seem that they want to deprecate the entire concept for assigns (and templates) as tests should not care about those internal decisions/mechanisms in such detail, so the gem is just as needed to transition to not requiring those instructions in a test suite in the future. https://blog.bigbinary.com/2016/04/19/changes-to-test-controllers-in-rails-5.html Thanks for the lead! – Pysis May 21 '19 at 15:21