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.

Beginning the tickets API<br />

Listing 13.22 spec/api/v1/projects_spec.rb<br />

context "index" do<br />

...<br />

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

it "XML" do<br />

get "#{url}.xml", :token => token<br />

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

end<br />

it "JSON" do<br />

get "#{url}.json", :token => token<br />

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

end<br />

end<br />

You’ve defined the let(:url) here to point to the nested route for tickets of a given<br />

project. This URL is currently undefined and so when you run this test with bin/rspec<br />

spec/api/v1/tickets_spec.rb, you’re told that the route you’re requesting doesn’t<br />

exist:<br />

Failure/Error: get "#{url}.json", :token => token<br />

ActionController::RoutingError:<br />

No route matches [GET] "/api/v1/projects/1/tickets.json"<br />

You can define this route easily inside config/routes.rb by changing these lines<br />

namespace :api do<br />

namespace :v1 do<br />

resources :projects<br />

end<br />

end<br />

to this:<br />

namespace :api do<br />

namespace :v1 do<br />

resources :projects do<br />

resources :tickets<br />

end<br />

end<br />

end<br />

Now you’ve got the tickets resource nested within projects for your API again. When<br />

you re-run this spec you’ll be told this:<br />

uninitialized constant Api::V1::TicketsController<br />

You can create this controller by creating a new file at app/controllers/api/v1/<br />

tickets_controller.rb. This controller needs to first of all respond to both JSON and<br />

XML, and find the project for each request using a before_filter. You can begin to<br />

define this controller using the code from the following listing.<br />

375

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

Saved successfully!

Ooh no, something went wrong!