Ruby

This getting started guide should help you get off the ground using Pact with Ruby. For more detail or advanced topics, head on over to the Ruby Pact GitHub repository.

Getting Started Guide

This workshop walks you through an example problem from start to finish, exploring most concepts that Pact supports. It takes approximately 2 hours to complete.

Installation

Add this line to your application’s Gemfile:

  1. gem 'pact'

And then execute:

  1. $ bundle

Or install it yourself as:

  1. $ gem install pact

Usage - an example scenario

We’re going to write an integration, with Pact tests, between a Consumer, the Zoo App, and its Provider, the Animal Service. In the Consumer project, we’re going to need to need a model (the Alligator class) to represent the data returned from the Animal Service, and a client (the AnimalServiceClient) which will be responsible for making the HTTP calls to the Animal Service.

Example

In the Zoo App (Consumer) project

1. Start with your model

Imagine a model class that looks something like this. The attributes for a Alligator live on a remote server, and will need to be retrieved by an HTTP call to the Animal Service.

  1. class Alligator
  2. attr_reader :name
  3. def initialize name
  4. @name = name
  5. end
  6. def == other
  7. other.is_a?(Alligator) && other.name == name
  8. end
  9. end

2. Create a skeleton Animal Service client class

Imagine an Animal Service client class that looks something like this.

  1. require 'httparty'
  2. class AnimalServiceClient
  3. include HTTParty
  4. base_uri 'http://animal-service.com'
  5. def get_alligator
  6. # Yet to be implemented because we're doing Test First Development...
  7. end
  8. end

3. Configure the mock Animal Service

The following code will create a mock service on localhost:1234 which will respond to your application’s queries over HTTP as if it were the real “Animal Service” app. It also creates a mock provider object which you will use to set up your expectations. The method name to access the mock service provider will be what ever name you give as the service argument - in this case animal_service

  1. # In /spec/service_providers/pact_helper.rb
  2. require 'pact/consumer/rspec'
  3. # or require 'pact/consumer/minitest' if you are using Minitest
  4. Pact.service_consumer "Zoo App" do
  5. has_pact_with "Animal Service" do
  6. mock_service :animal_service do
  7. port 1234
  8. end
  9. end
  10. end

4. Write a failing spec for the Animal Service client

  1. # In /spec/service_providers/animal_service_client_spec.rb
  2. # When using RSpec, use the metadata `:pact => true` to include all the pact functionality in your spec.
  3. # When using Minitest, include Pact::Consumer::Minitest in your spec.
  4. describe AnimalServiceClient, :pact => true do
  5. before do
  6. # Configure your client to point to the stub service on localhost using the port you have specified
  7. AnimalServiceClient.base_uri 'localhost:1234'
  8. end
  9. subject { AnimalServiceClient.new }
  10. describe "get_alligator" do
  11. before do
  12. animal_service.given("an alligator exists").
  13. upon_receiving("a request for an alligator").
  14. with(method: :get, path: '/alligator', query: '').
  15. will_respond_with(
  16. status: 200,
  17. headers: {'Content-Type' => 'application/json'},
  18. body: {name: 'Betty'} )
  19. end
  20. it "returns a alligator" do
  21. expect(subject.get_alligator).to eq(Alligator.new('Betty'))
  22. end
  23. end
  24. end

5. Run the specs

Running the AnimalServiceClient spec will generate a pact file in the configured pact dir (spec/pacts by default).
Logs will be output to the configured log dir (log by default) that can be useful when diagnosing problems.

Of course, the above specs will fail because the Animal Service client method is not implemented, so next, implement your provider client methods.

6. Implement the Animal Service client consumer methods

  1. class AnimalServiceClient
  2. include HTTParty
  3. base_uri 'http://animal-service.com'
  4. def get_alligator
  5. name = JSON.parse(self.class.get("/alligator").body)['name']
  6. Alligator.new(name)
  7. end
  8. end

7. Run the specs again.

Green! You now have a pact file that can be used to verify your expectations of the Animal Service provider project.

Now, rinse and repeat for other likely status codes that may be returned. For example, consider how you want your client to respond to a:

  • 404 (return null, or raise an error?)
  • 500 (specifying that the response body should contain an error message, and ensuring that your client logs that error message will make your life much easier when things go wrong)
  • 401/403 if there is authorisation.

In the Animal Service (Provider) project

1. Create the skeleton API classes

Create your API class using the framework of your choice (the Pact authors have a preference for [Webmachine][webmachine] and [Roar][roar]) - leave the methods unimplemented, we’re doing Test First Development, remember?

2. Tell your provider that it needs to honour the pact file you made earlier

Require pact/tasks in your Rakefile.

  1. # In Rakefile
  2. require 'pact/tasks'

Create a pact_helper.rb in your service provider project. The recommended place is spec/service_consumers/pact_helper.rb.

See Verifying Pacts and the configuration documentation for more information.

  1. # In specs/service_consumers/pact_helper.rb
  2. require 'pact/provider/rspec'
  3. Pact.service_provider "Animal Service" do
  4. honours_pact_with 'Zoo App' do
  5. # This example points to a local file, however, on a real project with a continuous
  6. # integration box, you would use a [Pact Broker](https://github.com/bethesque/pact_broker) or publish your pacts as artifacts,
  7. # and point the pact_uri to the pact published by the last successful build.
  8. pact_uri '../zoo-app/specs/pacts/zoo_app-animal_service.json'
  9. end
  10. end

3. Run your failing specs

  1. $ rake pact:verify

Congratulations! You now have a failing spec to develop against.

At this stage, you’ll want to be able to run your specs one at a time while you implement each feature. At the bottom of the failed pact:verify output you will see the commands to rerun each failed interaction individually. A command to run just one interaction will look like this:

  1. $ rake pact:verify PACT_DESCRIPTION="a request for an alligator" PACT_PROVIDER_STATE="an alligator exists"

4. Implement enough to make your first interaction spec pass

Rinse and repeat.

5. Keep going til you’re green

Yay! Your Animal Service Provider now honours the pact it has with your Zoo App Consumer. You can now have confidence that your Consumer and Provider will play nicely together.

Using provider states

Each interaction in a pact is verified in isolation, with no context maintained from the previous interactions. So how do you test a request that requires data to already exist on the provider? Read about provider states here.