HalSpec

Adds custom matchers for RSpec and step definitions for cucumber to validate and inspect Hypertext Application Language (the json version) responses (i.e. no xml support is included). Builds atop json_spec

Installation

Add this line to your application's Gemfile:

gem 'hal_spec'

And then execute:

$ bundle

Or install it yourself as:

$ gem install hal_spec

Usage

Rspec

This gem exposes all the matchers and helpers provided by json_spec (cf. their README) plus some HAL-specific matchers:

  • be_valid_hal

(the below example assumes use of the Roar gem for the MovieRepresenter class just for illustration purposes, it's not necessary at all)

  describe Movie
    let(:movie){ Movie.create!(title: "2001", cast: [Character.create(name: "HAL"), Character.create(name: "Dave")])  } 

    context "#to_json" do
      it "includes the associations" do
        Movie.extend(MovieRepresenter)
        movie.to_json should be_valid_hal
        movie.to_json should have_json_path("_embedded/cast")
        movie.to_json should have_json_size(2).at_path("_embedded/cast")
      end
    end 
  end

Cucumber

In your env.rb, add

require "hal_spec/cucumber"

(the json_spec gem requires that you define a last_json method in your support files, but this one doesn't, since it also validates headers from the response)

And use the steps in your responses.

(the example below had the cucumber-api-steps gem in mind but, again, not necessary)

Feature: Movie API
  Background:
    Given the following movies exist:
      | id | title                 |
      | 1  | 2001: a space odyssey |
      | 2  | 2010: odyssey two     |
    And the following characters exist:
      | id | name |
      | 1  | Dave |
    And character "Dave" appears in "2001: a space odyssey"
    And character "Dave" appears in "2010: odyssey two"

  Scenario: Show character endpoint
    When I send a GET request to "/characters/1"
    Then the HAL response should be:
      """
        {
          "_links": {
              "self": {"href": "/characters/1"}
          }
          ,"id": 1
          ,"name": "Dave"
          ,"_embedded": {
            "movies": [
                {
                   "_links": {"self": {"href": "/movies/1"}}
                  ,"id": 1
                  ,"name": "2001: a space odyssey"
                }
                ,{
                   "_links": {"self": {"href": "/movies/2"}}
                  ,"id": 2
                  ,"name": "2010: odyssey two"
                }
            ]
          }
        }
      """

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Added some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request