27.02.2013 Views

Rails%203%20In%20Action

Rails%203%20In%20Action

Rails%203%20In%20Action

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

528 CHAPTER 18 Rack-based applications<br />

By making it a class, you’ll be able to mount it in your application using the mount<br />

method in config/routes.rb. By mounting this Sinatra application, it will have access to<br />

all the classes from your Rails application, such as your models, which is precisely what<br />

you’re going to need for this new version of your API. You won’t use this code example<br />

right now; it’s handy to know that you can do this.<br />

To use Sinatra with your application, you’ll need to add it to the Gemfile with this<br />

line:<br />

gem 'sinatra'<br />

Then you’ll need to run bundle install to install it. So let’s go ahead now and start<br />

building this API using Sinatra. 5<br />

18.3.3 The API, by Sinatra<br />

Let’s create a new file to test your experimental new API at spec/api/v3/json/<br />

tickets_spec.rb. In this file you want to set up a project that has at least one ticket, as<br />

well as a user that you can use to make requests to your API. After that, you want to<br />

make a request to /api/v3/json/tickets and check that you get back a proper response<br />

of tickets. With this in mind, let’s write a spec that looks like the code shown in the following<br />

listing.<br />

Listing 18.7 spec/api/v3/json/tickets_spec.rb<br />

require 'spec_helper'<br />

describe Api::V3::JSON::Tickets, :type => :api do<br />

let(:project) { Factory(:project) }<br />

let(:user) { Factory(:user) }<br />

let(:token) { user.authentication_token }<br />

before do<br />

Factory(:ticket, :project => project)<br />

user.permissions.create!(:thing => project, :action => "view")<br />

end<br />

let(:url) { "/api/v3/json/projects/#{project.id}/tickets" }<br />

context "successful requests" do<br />

it "can get a list of tickets" do<br />

get url, :token => token<br />

last_response.body.should eql(project.tickets.to_json)<br />

end<br />

end<br />

end<br />

This test looks remarkably like the one in spec/api/v2/tickets_spec.rb, except this time<br />

you’re only testing for JSON responses and you’ve changed the URL that you’re<br />

requesting to api/:version/:format/:path. When you run this spec with bin/rspec<br />

spec/api/v3/json/tickets_spec.rb you’ll see that it’s giving you this error:<br />

... uninitialized constant Api::V3<br />

5 You can learn more about Sinatra at https://github.com/sinatra/sinatra/.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!