抱歉这个标题,我现在很沮丧,无法想出更好的东西。

我有一堂课, Judge, ,其中有一个方法 #stats. 。这 统计数据 方法应该向 api 发送 GET 请求并获取一些数据作为响应。我正在尝试对此进行测试并存根 stats 方法,以便我不会执行实际的请求。这就是我的测试的样子:

describe Judge do
  describe '.stats' do

    context 'when success' do
      subject { Judge.stats }

      it 'returns stats' do
        allow(Faraday).to receive(:get).and_return('some data')

        expect(subject.status).to eq 200
        expect(subject).to be_success
      end
    end
  end
end

这是我正在测试的课程:

class Judge

  def self.stats
    Faraday.get "some-domain-dot-com/stats"
  end

end

目前这给了我错误: Faraday does not implement: get那么如何用法拉​​第来解决这个问题呢?我见过这样的方法:

    stubs = Faraday::Adapter::Test::Stubs.new do |stub|
      stub.get('http://stats-api.com') { [200, {}, 'Lorem ipsum'] }
    end

但我似乎无法以正确的方式应用它。我在这里缺少什么?

有帮助吗?

解决方案

请注意,Faraday.new 返回 Faraday::Connection 的实例,而不是 Faraday。所以你可以尝试使用

allow_any_instance_of(Faraday::Connection).to receive(:get).and_return("some data")

请注意,我不知道返回问题中所示的“某些数据”是否正确,因为 Faraday::Connection.get 应该返回一个响应对象,其中包括正文和状态代码而不是字符串。你可以尝试这样的事情:

allow_any_instance_of(Faraday::Connection).to receive(:get).and_return(
   double("response", status: 200, body: "some data")
)

这是一个 Rails 控制台,显示您从 Faraday.new 返回的类

$ rails c
Loading development environment (Rails 4.1.5)
2.1.2 :001 > fara = Faraday.new
 => #<Faraday::Connection:0x0000010abcdd28 @parallel_manager=nil, @headers={"User-Agent"=>"Faraday v0.9.1"}, @params={}, @options=#<Faraday::RequestOptions (empty)>, @ssl=#<Faraday::SSLOptions (empty)>, @default_parallel_manager=nil, @builder=#<Faraday::RackBuilder:0x0000010abcd990 @handlers=[Faraday::Request::UrlEncoded, Faraday::Adapter::NetHttp]>, @url_prefix=#<URI::HTTP:0x0000010abcd378 URL:http:/>, @proxy=nil>
2.1.2 :002 > fara.class
 => Faraday::Connection

其他提示

法拉第类没有 get 方法,只有实例才这样做。由于您在类方法中使用它,因此您可以执行以下操作:

class Judge
  def self.stats
    connection.get "some-domain-dot-com/stats"
  end

  def self.connection=(val)
    @connection = val
  end

  def self.connection
    @connection ||= Faraday.new(some stuff to build up connection)
  end
end

然后在你的测试中你可以设置一个双精度:

let(:connection) { double :connection, get: nil }
before do
  allow(connection).to receive(:get).with("some-domain-dot-com/stats").and_return('some data')
  Judge.connection = connection
end

我遇到了同样的问题 Faraday::Adapter::Test::Stubs 错误与 Faraday does not implement: get. 。看来你需要设置 stubs 到法拉第适配器,如下所示:

  stubs = Faraday::Adapter::Test::Stubs.new do |stub|
    stub.get("some-domain-dot-com/stats") { |env| [200, {}, 'egg'] }
  end

  test = Faraday.new do |builder|
    builder.adapter :test, stubs
  end

  allow(Faraday).to receive(:new).and_return(test)

  expect(Judge.stats.body).to eq "egg"
  expect(Judge.stats.status).to eq 200
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top