如何使用`assigns`与Factory Girl

时间:2011-06-15 19:14:36

标签: ruby-on-rails unit-testing factory-bot

HIHO,

我有以下测试:

  test "should annoy Chuck Norris" do
    son = Factory.build(:son)
    assert_difference('Son.count') do
      post :create, son: { asset: son.asset, chuck_id: son.chuck }
    end

    assert_redirected_to chuck_path(assigns(son.chuck))
    assert_equal 'The world has been destroyed...', flash[:notice]
  end

assigns(son.chuck)不起作用,当我尝试son.chuck时,它有效,但在运行了所有测试并创建了一些Chucks后,Factory.build(:son)创建了{{1}标识为Chuck12正在发送标识assert_redirected_to。导致以下错误:

1

那么我怎样才能得到正确的Expected response to be a redirect to <http://test.host/chucks/12> but was a redirect to <http://test.host/chucks/1> /Users/edison/.rvm/gems/ruby-1.9.2-p180/gems/actionpack-3.1.0.rc4/lib/action_dispatch/testing/assertions/response.rb:67:in `assert_redirected_to'

1 个答案:

答案 0 :(得分:2)

我认为您要使用的是assigns(:chuck).son

分配的参数必须与控制器中的变量名匹配。换句话说,假设您在控制器中有@chuck.son,则应使用assigns(:chuck).son。请注意参数如何与@符号后面的内容相对应。