2011-01-24 51 views
2

我遇到了rspec2和rails 3的问题。仅当我直接调用它时,才调用存根方法,而不是如果它被同一类的方法调用。RSpec2:存根被另一个方法调用的方法

这是我的模型:

class Place < ActiveRecord::Base 
    def choose_a_winner_for_attack (p_attack) 
    puts "REAL choose_a_winner_for_attack" 
    (rand() < p_attack) 
    end 

    def attacks(attacked_place, attack_deployments) 
    …. 
    win = choose_a_winner_for_attack(p_attack) 
    …. 
    end 
end 

在规范,创建一个新的地方后,我存根它:

place.stub!(:choose_a_winner_for_attack).and_return(true) 

,然后我打电话:

place.choose_a_winner_for_attack 0 

它返回总是结束我永远不会看到日志“REAL choose_a_winner_for_attack”。

但如果我叫:

place.attacks(…) 

它调用真正的方法 “choose_a_winner_for_attack”(我看到日志 “REAL choose_a_winner_for_attack”)。

UPDATE 此规范的代码:

#Stub Place 
    place = @user0.place 
    place.stub!(:choose_a_winner_for_attack).and_return(true) 
    puts "INSIDE SPEC#{f.object_id} #{f.choose_a_winner_for_attack 0}" 
    place.attacks(other_place, deployments) 

这里有问题,我期待存根方法被调用。

+0

既然你没有显示真正的代码,你肯定有存根的对象,是一样的接收`attacks`方法? – nathanvda 2011-01-24 14:09:11

+0

我在choose_a_winner_for_attack里打印“place.object_id”和“object_id”,它们是一样的。 – Breezeight 2011-01-24 18:44:26

回答

1

不,它的工作原理:

class A 
    def foo 
    "foo" 
    end 

    def bar 
    foo 
    end 
end 

describe A do 
    it "stubs methods called from within other methods" do 
    a = A.new 
    a.stub(:foo).and_return("baz") 
    a.foo.should == "baz" # passes 
    a.bar.should == "baz" # passes 
    end 
end