RSpec - 尝试存根返回其自己参数的方法

ugo*_*chi 1 ruby rspec stubbing

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

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

allow(taxi_driver).to receive(:send_text).with(:string).and_return(string)
Run Code Online (Sandbox Code Playgroud)

这将返回:

allow(taxi_driver).to receive(:send_text).with(:string).and_return(string)
Run Code Online (Sandbox Code Playgroud)

如果我将返回参数更改为:string,则会收到以下错误:

NameError: undefined local variable or method 'string'
Run Code Online (Sandbox Code Playgroud)

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

Vas*_*fed 5

你可以传递一个块:

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