2

我对 rspec2 和 rails 3 有疑问。仅当我直接调用它时才调用存根方法,而不是由同一类的方法调用。

这是我的模型:

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”)。

更新 这是规范的代码:

  #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)

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

4

1 回答 1

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
于 2011-01-25T03:03:26.407 回答