2010-07-12 60 views
3

我有这样的例子:摩卡预期

# 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建成,以确保用户只会创造属于他们自己的东西。我使用的是预期非常相似,以确保它们从current_user对象调用find和它的作品找到,但在运行上面的例子,当我得到:

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: 
+0

我认为@profile从你的测试是不是在你的控制器current_user相同的对象。你能告诉我们用于设置@profile的代码吗? – robertokl 2010-07-12 19:40:29

+0

'@profile = @ cardset.profile'和'controller.stubs(:current_user).returns(@profile)'在测试前的':(每个)'调用中。正如我所说的,我还有另一个期望类似于''find'从'current_user'被调用的期望,这正是我处理那种通过的情况。 – trobrock 2010-07-12 23:37:18

+0

应该提到的一些新东西,我只是试着用这个'@ profile.cardsets.expects(:find).once.returns(@cardset)'写一个测试,它和我的'find_by_id'的期望完全一样,不起作用,所以它似乎只适用于提供的动态查找方法。 – trobrock 2010-07-13 02:50:04

回答

1

您添加的期望,@profile 后你” ve已存根从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