What's the purpose of assigns method in Rails tests (MiniTest)?
Asked Answered
F

2

26

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?

Foregoing answered 30/11, 2014 at 14:43 Comment(0)
K
34

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)
Kruller answered 2/12, 2014 at 7:27 Comment(0)
A
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.

Aynat answered 13/5, 2018 at 16:46 Comment(1)
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. blog.bigbinary.com/2016/04/19/… Thanks for the lead!Coin

© 2022 - 2024 — McMap. All rights reserved.