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.

382 CHAPTER 13 Designing an API<br />

your API. You’ll need to open these controllers and replace the multiple occurrences<br />

of Api::V1 with Api::V2.<br />

Strangely, version 2 of your API is, right now, identical to version 1 of your API.<br />

That’s intentional: a new version of the API should be an improvement, not an entirely<br />

new thing. With this separation, you can modify version 2 of the API as you please,<br />

leaving version 1 alone.<br />

Before deprecating the name field in your project responses, you’ll write a test to<br />

make sure that this is gone. This test will now test version 2 of the API, and so you’ll<br />

copy over the spec/api/v1 directory to spec/api/v2, also replacing occurrences of v1<br />

in these files with v2. The test for the new title field will now go in spec/api/v2/<br />

projects_spec.rb and will test that the projects viewable by this user action returns<br />

projects with title, and not name, using the code from the following listing to replace<br />

the JSON example in the index context.<br />

Listing 13.29 spec/api/v2/projects_spec.rb<br />

context "projects viewable by this user" do<br />

let(:url) { "/api/v2/projects" }<br />

let(:options) { { :except => :name, :methods => :title } }<br />

it "JSON" do<br />

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

body = Project.readable_by(user).to_json(options)<br />

last_response.body.should eql(body)<br />

last_response.status.should eql(200)<br />

projects = JSON.parse(last_response.body)<br />

projects.any? do |p|<br />

p["project"]["title"] == "Ticketee"<br />

end.should be_true<br />

projects.all? do |p|<br />

p["project"]["name"].blank?<br />

end.should be_true<br />

end<br />

end<br />

At the beginning of this test, you need to pass the same options to to_json B as you<br />

pass to respond_with, because the respond_with method generates the same output<br />

as to_json.<br />

In the final lines of this test, you’re checking that it’s now title and not name that<br />

returns the correct project title, and that the name key on all projects is blank. You’ll<br />

also need to change the XML test of this method to the code shown in the following<br />

listing.<br />

Listing 13.30 spec/api/v2/projects_spec.rb<br />

it "XML" do<br />

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

body = Project.readable_by(user).to_xml(options)<br />

B<br />

Pass<br />

options to<br />

to_json

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

Saved successfully!

Ooh no, something went wrong!