Stubbing with Faraday and Rspec

僤鯓⒐⒋嵵緔 提交于 2019-12-12 07:31:56

问题


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!


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/14329429/stubbing-with-faraday-and-rspec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!