创建新的stub方法,检查该方法是否存在于Rspec中



我想创建一些特殊的存根方法stub_checkstub_chain_check,以确保该方法存在。

例如:

#spec/controllers/payments_controller_spec.rb`
describe PaymentsController do
  it "makes a payment" do
    # Ensure method exists, Payment.new.respond_to?(:pay)
    # the API of Payment can change and tests will pass
    raise "Stubbing wrong method Payment#pay method doesn't exists" unless Payment.new.respond_to?(:pay)
    Payment.any_instance.stub(pay: true) # We can stub method now
    # Code...
  end
end

但是我想写Payment.stub_check(pay: true)

您可以在spec_helper上创建一个帮助器。rb文件:

def stub_check(resource, method, value, message)
  raise message unless resource.new.respond_to?(method)
  resource.any_instance.stub(method => value)
end

命名
stub_check(Payment, :pay, true, 'Stubbing wrong method Payment#pay method doesn't exists')

编辑:如果你想让它像存根一样工作,你可能需要修改mocka或你正在使用的匹配器(我猜它是mocka,因为"any_instance"方法)

最新更新