Mocha期望关联构建调用失败

时间:2010-07-12 17:58:14

标签: ruby-on-rails unit-testing rspec stub mocha

我有这个例子:

# GET New
context "on get to new" do
  it "should assign cardset" do
    @profile.cardsets.expects(:build).once.returns(Factory.stub(:cardset))
    get :new
    assigns[:cardset].should_not be_nil
  end
end

测试此方法:

# GET /cardsets/new
def new
  @cardset = current_user.cardsets.build
end

我试图强制关联是从current_user构建的,以确保用户只创建属于自己的东西。我使用期望非常相似,以确保他们从find对象调用current_user并且它可以找到,但是当运行上面的示例时,我得到:

6)
Mocha::ExpectationError in 'CardsetsController for a logged in user on get to new should assign cardset'
not all expectations were satisfied
unsatisfied expectations:
- expected exactly once, not yet invoked: [#<Cardset:0x102eaa8c8>, #<Cardset:0x102e12438>].build(any_parameters)
satisfied expectations:
- allowed any number of times, not yet invoked: ApplicationController.require_user(any_parameters)
- allowed any number of times, already invoked twice: #<CardsetsController:0x1030849c8>.current_user(any_parameters)

/Applications/MAMP/htdocs/my_app/spec/controllers/cardsets_controller_spec.rb:32:

1 个答案:

答案 0 :(得分:1)

您在之后将期望添加到@profile ,您已经存根从current_user返回它的函数。可能你需要做的是:

# GET New
context "on get to new" do
  it "should assign cardset" do
    @profile.cardsets.expects(:build).once.returns(Factory.stub(:cardset))
    controller.stubs(:current_user).returns(@profile)
    get :new
    assigns[:cardset].should_not be_nil
  end
end