ruby-on-rails - Rspec 模拟服务并接收整数

标签 ruby-on-rails ruby rspec

我想模拟一个将返回整数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

有错误

Failure/Error: allow(company_name_fetcher).to receive(:new).and_return { 1 }

ArgumentError: wrong number of arguments (given 0, expected 1+)

最佳答案

I want to mock a service that will returns the integer 1. In an endpoint it's called

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

and all of this line I want to mock to receive 1

选项 1 -allow_any_instance_of

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

选项 2 - 对构造函数进行 stub

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

关于ruby-on-rails - Rspec 模拟服务并接收整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58616857/

相关文章:

ruby-on-rails - Searchkick:Elasticsearch 没有索引 "FORBIDDEN/12/index read-only"?

ruby - 构建网站 - 使用 Ruby 的最佳实践和架构

ruby-on-rails - 具有多个关联的 RSpec/FactoryGirl 中的 "Name has already been taken"

ruby-on-rails - 如何在heroku上更新应用程序

jQuery 的 event.stopPropagation() 导致 Rails 出现问题 :remote => true

ruby-on-rails - Rails 3 与 2.3.5 渲染异常,代码为 :partial and :layout

java - 守护进程和脚本的 CAS 身份验证

ruby-on-rails - 带有参数的rails 4路线

ruby-on-rails - rake 规范给我错误

Ruby 检查与 Rspec 中的 to_s