我遇到了rspec2和rails 3的问题。只有当我直接调用它时才会调用stubbed方法,而不是由同一类的方法调用它。
这是我的模特:
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
它总是返回true结束我从未看到日志“REAL choose_a_winner_for_attack”。
但如果我打电话:
place.attacks(…)
它调用真正的方法“choose_a_winner_for_attack”(我看到日志“REAL choose_a_winner_for_attack”)。
更新 这是规范的代码:
#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)
这里有问题,我期待调用stubbed方法。
答案 0 :(得分: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