我有一个 Controller 规范,但我得到了以下失败的期望:
Failure/Error: put :update, :id => login_user.id, :user => valid_attributes
#<User:0xbd030bc> received :update_attributes with unexpected arguments
expected: ({:name=>"changed name", :email=>"changed@mail.com", :password=>"secret", :password_confirmation=>"secret"})
got: ({"name"=>"Test user", "email"=>"user@test.com", "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 => "changed@mail.com",:name=>"changed name"))
put :update, :id => login_user.id, :user => valid_attributes
end
end
我的有效属性有这样的东西:
def valid_attributes
{
:name => "Test user",
:email=> "user@test.com",
:password => "secret",
:password_confirmation => "secret"
}
end
那么我的参数有什么问题有什么建议吗?
我正在使用 Rails 3.0.5 和 rspec 2.6.0 ...
最佳答案
失败消息准确地告诉您发生了什么: User
的任何实例期待 update_attributes
散列包括 :email => "changed@mail.com"
,但它越来越:email => "user@test.com"
因为这就是 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
.有道理?
关于ruby-on-rails - rspec put 请求在我的 stub 上的正确参数是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6148806/