2011-05-27 47 views
4

我有一个控制器规范正确的参数和我获得以下失败的期望:什么是对我的存根rspec的PUT请求

Failure/Error: put :update, :id => login_user.id, :user => valid_attributes 
    #<User:0xbd030bc> received :update_attributes with unexpected arguments 
    expected: ({:name=>"changed name", :email=>"[email protected]", :password=>"secret", :password_confirmation=>"secret"}) 
      got: ({"name"=>"Test user", "email"=>"[email protected]", "password"=>"secret", "password_confirmation"=>"secret"}) 

对我来说,它看起来像我传递"name" => "Test User"和我期待:name => "test user"

我的规格如下所示:

describe 'with valid parameters' do 
     it 'updates the user' do 
     login_user = User.create!(valid_attributes) 
     controller.stub(:current_user).and_return(login_user) 
     User.any_instance. 
      should_receive(:update_attributes). 
      with(valid_attributes.merge(:email => "[email protected]",:name=>"changed name")) 
     put :update, :id => login_user.id, :user => valid_attributes 
     end 
end 

,我有这样的事情对我有效的属性:

def valid_attributes 
    { 
    :name => "Test user", 
    :email=> "[email protected]", 
    :password => "secret", 
    :password_confirmation => "secret" 

    } 
end 

那么我的参数有什么问题有什么建议吗?

我用Rails 3.0.5与2.6.0的RSpec ...

回答

8

失败的消息告诉你到底发生了什么:中User任何实例期待update_attributes与包括:email => "[email protected]"哈希,但它变得:email => "[email protected]"因为这就是valid_attributes。同样,它期望:name => "changed_name",但得到:name => "Test user",因为那是valid_attributes

你可以简化这个例子,避免这种混淆。无需在此处使用valid_attributes,因为should_receive无论如何都会拦截update_attributes调用。我通常做像这样:

controller.stub(:current_user).and_return(mock_model(User)) # no need for a real user here 
User.any_instance. 
    should_receive(:update_attributes). 
    with({"these" => "params"}) 
put :update, :id => login_user.id, :user => {"these" => "params"} 

这样的预期值和实际值是正确的例子,它清楚地表明,它其实并不重要,他们是什么:无论哈希传递作为:user传递直接到update_attributes

有意义吗?

+0

是有道理,有效......我只是期待如果我在我的put qequest中传入了我的valid_attributes,它们与我将它们传递给with方法时一样,就是这样。但你的方式工作......谢谢 – 2011-05-27 09:48:44