RSpec - 试图存根 returns 自己的参数的方法

RSpec - trying to stub a method that returns its own argument

我想在我的单元测试中删除一个方法。使用一个参数(一个字符串)调用真正的方法,然后发送一条文本消息。我需要删除该方法,但 return 作为参数传入的字符串。

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

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

这个returns:

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

My method is being called like this: send_text("the time now is #{Time.now}"). The string varies according to the time, thats why I need the mock to return the varying string. Perhaps its not within the scope of a mock to do this?

在这种情况下,我通常使用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