2010-05-07 145 views
4

我有一個rspec模擬對象,值被賦值爲屬性。我很努力地在我的rspec測試中達到這個期望值。只是想知道sytax是什麼?代碼:rspec嘲諷對象屬性賦值

def create 
@new_campaign = AdCampaign.new(params[:new_campaign]) 
@new_campaign.creationDate = "#{Time.now.year}/#{Time.now.mon}/#{Time.now.day}" 
if @new_campaign.save 
    flash[:status] = "Success" 
else 
    flash[:status] = "Failed" 
end end 

測試

it "should able to create new campaign when form is submitted" do 
    campaign_model = mock_model(AdCampaign) 
    AdCampaign.should_receive(:new).with(params[:new_campaign]).and_return(campaign_model) 
    campaign_model.should_receive(:creationDate).with("#{Time.now.year}/#{Time.now.mon}/#{Time.now.day}")campaign_model.should_receive(:save).and_return(true) 
    post :create 

    flash[:status].should == 'Success' 
    response.should render_template('create') end 

問題是我收到此錯誤:

Spec::Mocks::MockExpectationError in 'CampaignController new campaigns should able to create new campaign when form is submitted' Mock "AdCampaign_1002" received unexpected message :creationDate= with ("2010/5/7") 

讓我怎麼設置對象的屬性分配的期望呢?

感謝

回答

12

Ruby中沒有「屬性賦值」這樣的事情。在Ruby中,的一切都是是一個方法調用。所以,你嘲笑setter方法,就像對其他任何方法:

campaign_model.should_receive(:creationDate=).with(...) 

BTW:這些測試打印出的診斷消息不只是shpw。在這種情況下,消息已經告訴你你需要知道的一切:

Spec::Mocks::MockExpectationError in 'CampaignController new campaigns should able to create new campaign when form is submitted' Mock "AdCampaign_1002" received unexpected message :creationDate= with ("2010/5/7")

正如你所看到的,你發佈已經告訴你什麼是方法的名稱是你需要模擬消息在那裏:

unexpected message :creationDate= with ("2010/5/7") 
        ^^^^^^^^^^^^^^ 
0

找到關於它的here

鏈接這是通過簡單地添加:creationDate =而並非只是:creationDate的期望。

+0

+您還可以使用(:createionDate =)。with() – charleetm 2010-05-07 10:42:39