Concise tests for resourceful web APIs
Have you ever developed a web API and spent more time writing its tests and documentation than its code?
Have you ever built a web site that depends on third-party APIs and wondered how to test their result?
Wonder no more: RSpecApi helps you take care of these cases with concise and self-documenting tests.
concerts_spec.rbresource :concert do
host 'http://myconcerts.herokuapp.com'
has_attribute :id, type: {number: :integer}
has_attribute :where, type: :string
has_attribute :website, type: [:null, string: :url]
get '/concerts', collection: true do
respond_with :ok
end
post '/concerts' do
respond_with :created, concert: {where: 'Coachella'}
respond_with :unprocessable_entity, concert: {where: nil}
end
end
The few lines of code above document two API endpoints that http://myconcerts.herokuapp.com
provides:
GET /concerts
always responds with200 OK
and returns a collection of concert resources.
Each concert has anid
field (Integer), awhere
field (String), and awebsite
field (URL or nil)POST /concerts
responds with201 Created
when given valid concert data in the request body.
In this case, the response contains the new concert resource (withid
,where
, andwebsite
). Otherwise, the endpoint responds with422 Unprocessable Entity
Ensuring that this documentation is valid and that http://myconcerts.herokuapp.com
complies with these promises
is as easy as running the following commands:
$ gem install rspec-api
$ rspec --require rspec-api concerts_spec.rb
Concerts
Getting a list of concerts
GET /concerts
responds with a status code that
should be 200
responds with headers that
should include 'Content-Type': 'application/json; charset=utf-8'
responds with a body that
should be a collection
should have attributes :id (Integer) and :where (String)
Creating one concert
POST /concerts with concert: {:where=>"Coachella"}
responds with a status code that
should be 201
responds with headers that
should include 'Content-Type': 'application/json; charset=utf-8'
responds with a body that
should have attributes :id (Integer) and :where (String)
POST /concerts with concert: {:where=>nil}
responds with a status code that
should be 422
responds with headers that
should include 'Content-Type': 'application/json; charset=utf-8'
Finished in 0.00334 seconds
6 examples, 0 failures
All the expectations pass, so we are good to go! We have successfully tested that the API keeps its promises.