【问题标题】:Rspec mock service and receive integerRspec模拟服务并接收整数
【发布时间】:2019-10-30 07:57:37
【问题描述】:

我想模拟一个将返回整数 1 的服务。在端点中它被称为

CompanyNameFetcher.new(params[:filters][:company_name].downcase).call

我想模拟所有这行以接收1

这是我目前所拥有的:

      let(:company_name_fetcher) do
        class_double CompanyNameFetcher
      end
      before do
        allow(company_name_fetcher).to receive(:new).and_return { 1 }
      end

有错误

失败/错误:allow(company_name_fetcher).to receive(:new).and_return { 1 }

参数错误: 参数数量错误(给定 0,预期 1+)

【问题讨论】:

  • 我想你希望CompanyNameFetcher 接收:call 并返回1,对吗?显然,new 需要一些参数,而您没有将它们传递进去。因此,我想是错误。

标签: ruby-on-rails ruby rspec


【解决方案1】:

我想模拟一个将返回整数 1 的服务。在端点中它被称为

CompanyNameFetcher.new(params[:filters][:company_name].downcase).call

我想模拟所有这行以接收 1

选项 1 - allow_any_instance_of

allow_any_instance_of(CompanyNameFetcher).to( 
  receive(:call).and_return(1)
)

选项 2 - 存根构造函数

mock_fetcher = instance_double(CompanyNameFetcher)
allow(CompanyNameFetcher).to( 
  receive(:new).and_return(mock_fetcher)
)
allow(mock_fetcher).to rececive(:call).and_return(1)

【讨论】:

    猜你喜欢
    • 2016-11-27
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 2018-10-07
    • 1970-01-01
    • 2019-08-21
    相关资源
    最近更新 更多