rspec模拟对象属性赋值

时间:2010-05-07 09:36:28

标签: ruby-on-rails ruby rspec

我有一个rspec模拟对象,一个值被赋值为属性。我很难在我的rspec测试中满足这种期望。只是想知道sytax是什么?代码:

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")

那么我如何设置对象属性赋值的期望?

由于

2 个答案:

答案 0 :(得分:13)

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")
                    ^^^^^^^^^^^^^^

答案 1 :(得分:0)

找到关于它的链接here

这只需添加:creationDate =而不仅仅是:期望中的creationDate。