RSpeC语言 尝试存根返回其自身参数的方法



我有一个方法,我试图在我的单元测试中存根。真正的方法使用一个参数(字符串)调用,然后发送一条文本消息。我需要存根方法,但返回作为参数传入的字符串。

我在 RSpec 测试中的代码是这样的:

allow(taxi_driver).to receive(:send_text).with(:string).and_return(string)

这将返回:

NameError: undefined local variable or method 'string'

如果我将 return 参数更改为 :string ,则会出现以下错误:

Please stub a default value first if message might be received with other args as well

我尝试过谷歌搜索和检查 relishapp.com 网站,但找不到看起来非常简单明了的答案。

你可以传递一个块:

allow(taxi_driver).to receive(:send_text).with(kind_of(String)){|string| string }
expect(taxi_driver.send_text("123")).to eq("123")

我的方法被调用如下:send_text("现在的时间是#{Time.now}")。字符串根据时间而变化,这就是为什么我需要模拟来返回变化的字符串。也许这样做不在模拟的范围内?

在这种情况下,我通常使用 Timecop gem 来冻结系统时间。下面是一个示例用例:

describe "#send_text" do
  let(:taxi_driver) { TaxiDriver.new }
  before do
    Timecop.freeze(Time.local(2016, 1, 30, 12, 0, 0))
  end
  after do
    Timecop.return
  end
  example do
    expect(taxi_driver.send_text("the time now is #{Time.now}")).to eq 
      "the time now is 2016-01-30 12:00:00 +0900"
  end
end

最新更新