Stop with Faraday and Rspec

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\ 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 does not really satisfy me, because all I am testing is that I am doing POST with Faraday, but I cannot check the URL, headers or body, as they went through the block. I tried using the Faraday testing adapter, but I don't see any way to test the URL, headers or body with this.

Is there a better way to write my rspec stub? Or can I use the Faraday testing adapter in some way that I could not understand about?

Thanks!

+4
source share
2 answers

My friend @ n1kh1l pointed me to the and_yield Rspec method and this SO post, which allows me to write my test as follows:

 require 'spec_helper' describe Gist do context '.create' do it 'POSTs a new Gist to the user\ 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 
+7
source

You can use the excellent WebMock library for stub requests and check the expectations that the request was made, see the documents

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 
+4
source

All Articles