27.02.2013 Views

Rails%203%20In%20Action

Rails%203%20In%20Action

Rails%203%20In%20Action

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

374 CHAPTER 13 Designing an API<br />

The entire projects API is now complete. What you’ve got at the moment is a solid<br />

base for version 1 of Ticketee’s projects API. You’ll now see how you can begin creating<br />

the nested API for tickets on a project.<br />

13.2 Beginning the tickets API<br />

In this section you’ll begin to create an API for tickets on a project. You’re only going<br />

to be creating the part of the API to list tickets for now, because the remaining parts<br />

are similar in style to what you saw with the projects API. This section will give you a<br />

taste of how to work with nested resources within the context of an API.<br />

The first part you’re going to need for this API is two tests: one to make sure you<br />

can get XML results back from this API and another for JSON results. Put these new<br />

tests in a new file at spec/api/v1/tickets_spec.rb, beginning with the setup required for<br />

both of these tests shown in the following listing.<br />

Listing 13.21 spec/api/v1/tickets_spec.rb<br />

require 'spec_helper'<br />

describe "/api/v1/tickets", :type => :api do<br />

let(:project) { Factory(:project, :name => "Ticketee") }<br />

before do<br />

@user = create_user!<br />

@user.update_attribute(:admin, true)<br />

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

:thing => project)<br />

end<br />

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

In this spec you use a before block to set up your user, rather than using a let as you<br />

did in spec/api/v1/projects_spec.rb. The reason for this is when a let is referenced,<br />

the block is re-run. If you were to create five tickets and reference a user object set up<br />

with let, it would create five users. This problem becomes way more pronounced<br />

when you create 100 objects, each referencing the let.<br />

With this setup, you can begin the context for your index action and then in a<br />

before block, create 20 tickets for the project by using these lines after the<br />

let(:project) line:<br />

context "index" do<br />

before do<br />

5.times do<br />

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

end<br />

end<br />

Finally, you can write the XML and JSON tests by placing the code shown in the following<br />

listing inside the context block you have written.

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

Saved successfully!

Ooh no, something went wrong!