【发布时间】:2011-08-21 17:40:58
【问题描述】:
虽然我的问题很简单,但我在这里找不到答案:
如何存根方法并返回参数本身(例如在执行数组操作的方法上)?
类似这样的:
interface.stub!(:get_trace).with(<whatever_here>).and_return(<whatever_here>)
【问题讨论】:
标签: ruby parameters rspec return-value stubbing
虽然我的问题很简单,但我在这里找不到答案:
如何存根方法并返回参数本身(例如在执行数组操作的方法上)?
类似这样的:
interface.stub!(:get_trace).with(<whatever_here>).and_return(<whatever_here>)
【问题讨论】:
标签: ruby parameters rspec return-value stubbing
注意:stub 方法已被弃用。请参阅this answer 了解执行此操作的现代方式。
stub! 可以接受一个块。块接收参数;块的返回值就是存根的返回值:
class Interface
end
describe Interface do
it "should have a stub that returns its argument" do
interface = Interface.new
interface.stub!(:get_trace) do |arg|
arg
end
interface.get_trace(123).should eql 123
end
end
【讨论】:
存根方法已被期望弃用。
expect(object).to receive(:get_trace).with(anything) do |value|
value
end
https://relishapp.com/rspec/rspec-mocks/v/3-2/docs/configuring-responses/block-implementation
【讨论】:
allow而不是expect吗?
您可以使用allow(存根)代替expect(模拟):
allow(object).to receive(:my_method_name) { |param1, param2| param1 }
使用命名参数:
allow(object).to receive(:my_method_name) { |params| params[:my_named_param] }
这是一个真实的例子:
假设我们有一个S3StorageService,它使用upload_file 方法将我们的文件上传到S3。该方法将 S3 直接 URL 返回到我们上传的文件。
def self.upload_file(file_type:, pathname:, metadata: {}) …
出于多种原因(离线测试、性能改进……),我们希望对上传进行存根:
allow(S3StorageService).to receive(:upload_file) { |params| params[:pathname] }
那个存根只返回文件路径。
【讨论】: