Stubbing with Faraday and Rspec

2019-03-16 12:08发布

I have a model that looks like this:

class Gist
    def self.create(options)
    post_response = Faraday.post do |request|
      request.url 'https://api.github.com/gists'
      request.headers['Authorization'] = "Basic " + Base64.encode64("#{GITHUB_USERNAME}:#{GITHUB_PASSWORD}")
      request.body = options.to_json
    end
  end
end

and a test that looks like this:

require 'spec_helper'

describe Gist do
  context '.create' do
    it 'POSTs a new Gist to the user\'s account' do
      Faraday.should_receive(:post)
      Gist.create({:public => 'true',
                   :description => 'a test gist',
                   'files' => {'test_file.rb' => 'puts "hello world!"'}})
    end
  end
end

This test doesn't really satisfy me, though, as all I'm testing is that I'm making some POST with Faraday, but I can't actually test the URL, headers, or body, since they're passed in with a block. I tried to use the Faraday test adaptor, but I don't see any way of testing the URL, headers, or body with that, either.

Is there a better way to write my Rspec stub? Or am I able to use the Faraday test adaptor in some way I haven't been able to make sense of?

Thanks!

2条回答
聊天终结者
2楼-- · 2019-03-16 13:00

My friend @n1kh1l pointed me to the and_yield Rspec method and this SO post that let me write my test like this:

require 'spec_helper'

describe Gist do
  context '.create' do
    it 'POSTs a new Gist to the user\'s account' do
      gist = {:public => 'true',
              :description => 'a test gist',
              :files => {'test_file.rb' => {:content => 'puts "hello world!"'}}}

      request = double
      request.should_receive(:url).with('https://api.github.com/gists')
      headers = double
      headers.should_receive(:[]=).with('Authorization', "Basic " + Base64.encode64("#{GITHUB_USERNAME}:#{GITHUB_PASSWORD}"))
      request.should_receive(:headers).and_return(headers)
      request.should_receive(:body=).with(gist.to_json)
      Faraday.should_receive(:post).and_yield(request)

      Gist.create(gist)
    end
  end
end
查看更多
Explosion°爆炸
3楼-- · 2019-03-16 13:12

You can use the excellent WebMock library to stub requests and test for expectations that a request has been made, see the docs

In your code:

Faraday.post do |req|
  req.body = "hello world"
  req.url = "http://example.com/"
end

Faraday.get do |req|
  req.url = "http://example.com/"
  req.params['a'] = 1
  req.params['b'] = 2
end

In the RSpec file:

stub = stub_request(:post, "example.com")
  .with(body: "hello world", status: 200)
  .to_return(body: "a response to post")
expect(stub).to have_been_requested

expect(
  a_request(:get, "example.com")
    .with(query: { a: 1, b: 2 })
).to have_been_made.once
查看更多
登录 后发表回答