Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Testing Third Party Integrations

Testing Third Party Integrations

Dive into several strategies for testing third party interactions, with an emphasis on:

- stubbing at the network layer
- stubbing the adapter
- using a fake adapter

Stephanie Viccari

January 06, 2021
Tweet

More Decks by Stephanie Viccari

Other Decks in Education

Transcript

  1. Why Should Tests Avoid API Calls? • Deterministic tests •

    Faster tests • Prevent changing data on a staging or production environment 2
  2. Stubbing the Adapter RSpec.describe ShoppingCart do describe "#tax" do it

    "calculates a 10% tax rate" do item = create(:item) shopping_cart = ShoppingCart.new(item) allow(QuoteService).to receive(:fetch).and_return(100) expect(shopping_cart.tax).to eq 10 end end end # This approach is useful when unit-testing objects that # depend on data from other services. 5
  3. Stubbing HTTP Requests RSpec.describe ShoppingCart do describe "#tax" do it

    "calculates a 10% tax rate" do item = create(:item) shopping_cart = ShoppingCart.new(item) stub_request("http://quote-service.com/prices").and_return( { pricesRequest: { regularPrice: 100 } }.to_json ) expect(shopping_cart.tax).to eq 10 end end end 7
  4. Using a Fake Adapter RSpec.describe ShoppingCart do describe "#tax" do

    it "calculates a 10% tax rate" do item = create(:item) fake_quote_service = FakeQuoteService.new(price: 100) shopping_cart = ShoppingCart.new(item, quote_service: fake_quote_service) expect(shopping_cart.tax).to eq 10 end end end 9
  5. # spec/support/fake_quote_service.rb class FakeQuoteService < Sinatra::Base get "/prices/:id" do content_type

    :json status 200 { pricesRequest: { regularPrice: 100 } }.to_json end end # rails_helper.rb RSpec.configure do |config| config.before(:each) do stub_request(:any, /quote-service.com/).to_rack(FakeQuoteService) end end 11
  6. Feature Request When I visit the homepage for the New

    York Adventure Club, I want to see the name, date, and venue for the next upcoming event. 12
  7. Outline • Shameless Green (issue real network calls) • Stub

    HTTP Requests • Stub methods on an Adapter • Replace the Adapter with a Fake Adapter 13
  8. Resources Custom Formats for DateTime - https://thoughtbot.com/blog/custom-formats-for-datetime Testing Third Party

    Interactions - https://thoughtbot.com/blog/testing-third-party- interactions Testing Interaction with 3rd-party APIs - https://thoughtbot.com/upcase/videos/testing- interaction-with-3rd-party-apis How to Stub External Services in Tests - https://thoughtbot.com/blog/how-to-stub-external- services-in-tests Faking APIs in Development and Staging - https://thoughtbot.com/blog/faking-apis-in-development- and-staging 15