在Rails测试(MiniTest)中分配方法的目的是什么?

Dan*_*Dan 23 ruby-on-rails minitest

用于自动生成的测试:

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
Run Code Online (Sandbox Code Playgroud)

Rails 文档没有任何描述.这种方法的目的是什么以及如何使用它?

Ani*_*rya 29

这意味着控制器是否定义了实例变量@item="something".您可以使用例如在测试中获取实例变量

# It will check if the instance variable is a string.
assert_kind_of String, assigns(:item)
Run Code Online (Sandbox Code Playgroud)


wot*_*oto 6

请注意assigns在 Rails 5 中已弃用。并提取到单独的 gem。要使用它,您必须在您的 gemfile 中包含 'rails-controller-testing'。

  • 因为我很好奇,所以想澄清一下,找到了这篇文章,而且他们似乎确实想弃用分配(和模板)的整个概念,因为测试不应该如此详细地关心这些内部决策/机制,所以宝石只是根据需要过渡到将来在测试套件中不需要这些指令。https://blog.bigbinary.com/2016/04/19/changes-to-test-controllers-in-rails-5.html 感谢您的领导! (2认同)