2012-09-25 74 views
1

我有以下如何比較Rspec中的分配?

it 'should assign a new profile to user' do 
    get :new 
    assigns(:user_profile).should ==(Profile.new) 
end 

但它不工作。我試過'eql?'和'平等'?分別。如何比較它以便了解@user_profile的內容是否爲Profile.new?

我曾經做過一個解決方法,做一個指定變量的.class,檢查它是否是Profile,但我想停止這些不好的做法。

謝謝。

回答

1

這裏的問題是Object.new被設計調用兩次創建兩個不同對象,這是不相等的。

1.9.2p318 :001 > Object.new == Object.new 
=> false 

有一兩件事你可以在這裏做是

let(:profile){ Profile.new } 

it 'should assign a new profile to user' do 
    Profile.should_receive(:new).and_return profile 
    get :new 
    assigns(:user_profile).should eq profile 
end 

現在你沒有真正創建一個新的配置文件時,控制器動作被調用,但你仍然考驗這個Profile正在接收new,和您正在測試該方法的返回值是由控制器分配給@user_profile

+0

令人敬畏的兄弟,這正是我想要的! ;-) – thiagofm

+0

事實上,沒有什麼特別的理由可以使'profile'的值成爲實際的'Profile'對象;它可以是任何東西。例如,'let(:profile){「一個新的配置文件」}'不會真的改變測試的功能。但沒關係,因爲在控制器測試中,你不想測試'Profile :: new'本身的功能。但是,如果在控制器操作的'@ user_profile'上調用其他方法,這可能會導致消息期望錯誤。 (然後另一個選項是'let(:profile){mock('Profile')。as_null_object}'。) – gregates