Archive

Posts Tagged ‘rspec’

如何stub实例方法

November 19th, 2010 yakjuly 2 comments

rspec测试 controller。
在Factory构建数据的时候,需要调用一些方法,而这些方法无法在测试controller中通过实例来模拟。

例如,

class A < ActiveRecord::Base
  def before_save
    self.url = do_something
  end

  def do_something(arg=nil)
    42
  end

end

你希望在before_save的时候 将do_something的结果 修改为 24. 在测试 controller的时候怎么办呢?

new_method = A.method(:new)
A.stub!(:new).and_return do |*args|
  a = new_method.call(*args)
  a.should_receive(:do_something).with(any_args()).and_return(24)
  a
end

以上只适用于 new 出来的 实例。

A.any_instance.stubs(:do_something).returns(24)
Categories: rails, rspec, ruby Tags: