简体   繁体   中英

Stuck with Faraday in rspec

I'm trying to write a test calling an API using Faraday with RSpec. The calling is in the .execute method and it works normally in production, but in test, I'm stuck with this error:

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 . It records your external request into a cassette and on spec run it plays back.

Cheers!

Because in test mode, you did's set the url ,I can replay the exact error in my pry console:

> 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.

There is also something called Webmock, which mocks the API call and returns a response that you predefined. 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.

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}"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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