简体   繁体   English

卡在 rspec 中的法拉第

[英]Stuck with Faraday in rspec

I'm trying to write a test calling an API using Faraday with RSpec.我正在尝试使用 Faraday 和 RSpec 编写一个调用 API 的测试。 The calling is in the .execute method and it works normally in production, but in test, I'm stuck with this error:调用在 .execute 方法中,它在生产中正常工作,但在测试中,我遇到了这个错误:

Failure/Error: @response ||= conn.post '/oauth/token', @params

     Faraday::ConnectionFailed:
       Failed to open TCP connection to :80 (Connection refused - connect(2) for nil port 80)

And the test is like this而测试是这样的

it 'access_token should not be nil' do
      @auth = AuthenticateService.new(params)
      auth_exec = @auth.execute
      access_token = auth_exec[:access_token]
      expect(access_token.present?).not_to be_empty
    end

Do I need to configure something to make Faraday works with test?我是否需要配置一些东西才能使法拉第与测试一起工作?

It's actually trying to call a outsider request.它实际上是在尝试调用外部请求。 In you case there are two solutions:在您的情况下,有两种解决方案:

Mock what is calling outside:模拟什么在外面打电话:

before do
  allow_any_instance_of(AuthenticateService).to receive(:execute).and_return(access_token: 'some token')
end

Record a real call (I like it :))录制一个真实的通话(我喜欢它:))

You can try a gem vcr .你可以试试 gem vcr It records your external request into a cassette and on spec run it plays back.它将您的外部请求记录到cassette并在规范运行时播放。

Cheers!干杯!

Because in test mode, you did's set the url ,I can replay the exact error in my pry console:因为在测试模式下,您确实设置了url ,所以我可以在我的 pry 控制台中重播确切的错误:

> conn = Faraday.new();
> conn.post '/oauth/token';
Faraday::ConnectionFailed: Connection refused - connect(2) for nil port 80
from /home/fangxing/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/net/http.rb:879:in `initialize'

I think in your project somewhere, configured a variable url for Faraday, and you did't configure it in test mode.我想在你的项目中某处,为法拉第配置了一个变量url ,而你没有在测试模式下配置它。

There is also something called Webmock, which mocks the API call and returns a response that you predefined.还有一个叫做 Webmock 的东西,它模拟 API 调用并返回一个你预定义的响应。 You should look into it!你应该调查一下!

I like it a lot better than VCR, which could be nasty when dealing with a lot of data or multiple API calls.我比 VCR 更喜欢它,它在处理大量数据或多个 API 调用时可能会很糟糕。

My solution to a similar problem:我对类似问题的解决方案:

stub_request(method, url).with(
  headers: { 'Authorization' => /Basic */ }
).to_return(
  status: status, body: 'stubbed response', headers: {}
)

you can tighten verification by replacing:您可以通过替换来加强验证:

/Basic */ -> "Basic #{your_token}"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM