Reputation: 1991
I've a problem with rspec2 and rails 3. A stubbed method is called only if I call it directly, not if it's called by a method of the same class.
This is my model:
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
In the spec, after Creating a new place, I stub it:
place.stub!(:choose_a_winner_for_attack).and_return(true)
and then I call:
place.choose_a_winner_for_attack 0
it return always true end I never see the log "REAL choose_a_winner_for_attack".
But if I call:
place.attacks(…)
it call the real method "choose_a_winner_for_attack" (I see the log "REAL choose_a_winner_for_attack").
UPDATE This the code of the spec:
#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)
Here there is the problem, I was expecting the stubbed method is called.
Upvotes: 2
Views: 2308
Reputation: 47578
Nope, it works:
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
Upvotes: 1