Skip to content

Instantly share code, notes, and snippets.

@bkeepers
Created Sep 20, 2013
Embed
What would you like to do?
Use HyperClient to test your Hypermedia API
# spec/features/api_spec.rb
require 'spec_helper'
describe 'API' do
class TestClient < Hyperclient::EntryPoint
def default_faraday_block
lambda do |faraday|
faraday.request :json
faraday.response :json, content_type: /\bjson$/
faraday.adapter :rack, Capybara.app
end
end
def default_headers
super.merge 'Accept' => MyApp::MediaType
end
end
let(:client) { TestClient.new('/') }
shared_examples 'paginated events' do
it 'has embedded events' do
subject.embedded.event.should be_instance_of(Array)
subject.embedded.event.first.attributes.name.should == event.name
end
it 'has a self link' do
subject.links['self'].url.should == self_link
end
end
describe 'search', :search => true do
let!(:event) { create :event, :published, :name => 'Hypermedia' }
subject { client.links.search.expand(:q => 'hypermedia') }
it_behaves_like 'paginated events' do
let(:self_link) { search_index_url :q => 'hypermedia', :page => 1 }
end
end
describe 'category' do
let!(:category) { create :category }
let!(:event) { create :event, :published, :category => category }
context 'embbedded in the root' do
subject { client.embedded.category.first }
it { subject.attributes.name.should == category.name }
end
it_behaves_like 'paginated events' do
subject { client.embedded.category.first.links.events }
let(:self_link) { category_url category, :page => 1 }
end
end
describe 'crawling the api' do
let!(:category) { create :category }
let!(:event) { create :event, :featured, :category => category }
before do
user.star(event)
@crawled = Set.new
end
it 'returns valid links' do
crawl client
@crawled.should include(
root_url,
category_url(category, :page => 1),
event_url(event)
)
end
def crawl(link)
return if link.templated? ||
@crawled.include?(link.url) ||
(link.type && link.type != MyApp::MediaType)
@crawled.add link.url
response = link.get
response.status.should == 200
response.headers['Content-Type'].should include(MyApp::MediaType)
links_from_resource(link.resource).each do |link|
crawl link
end
end
def links_from_resource(resource)
links = resource.embedded.map do |name, embed|
Array(embed).map {|e| links_from_resource(e) }
end.flatten
links + resource.links.values.flatten
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment