Sir*_*lot 22 ruby parameters rspec return-value stubbing
虽然我的问题非常简单,但我在这里找不到答案:
如何存根方法并返回参数本身(例如,在执行数组操作的方法上)?
像这样的东西:
interface.stub!(:get_trace).with(<whatever_here>).and_return(<whatever_here>)
Run Code Online (Sandbox Code Playgroud)
Way*_*rad 29
注意:不推荐使用存根方法.请参阅此答案,了解现代方法.
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
Run Code Online (Sandbox Code Playgroud)
小智 18
存根方法已被弃用,有利于期望.
expect(object).to receive(:get_trace).with(anything) do |value|
value
end
Run Code Online (Sandbox Code Playgroud)
https://relishapp.com/rspec/rspec-mocks/v/3-2/docs/configuring-responses/block-implementation
小智 5
您可以使用allow
(存根)代替expect
(模拟):
allow(object).to receive(:my_method_name) { |param1, param2| param1 }
Run Code Online (Sandbox Code Playgroud)
使用命名参数:
allow(object).to receive(:my_method_name) { |params| params[:my_named_param] }
Run Code Online (Sandbox Code Playgroud)
这是一个现实生活中的例子:
假设我们有一个S3StorageService
使用该upload_file
方法将我们的文件上传到 S3 的。该方法将 S3 直接 URL 返回到我们上传的文件。
def self.upload_file(file_type:, pathname:, metadata: {}) …
Run Code Online (Sandbox Code Playgroud)
出于多种原因(离线测试、性能改进……),我们希望对上传进行存根:
allow(S3StorageService).to receive(:upload_file) { |params| params[:pathname] }
Run Code Online (Sandbox Code Playgroud)
该存根仅返回文件路径。