2011-05-27 21 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