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.

The projects API<br />

another called project, and then check to see if its text is equal to the name of your<br />

project, which it should be if everything works out fine. When you run bin/rspec<br />

spec/api/v1/projects_spec.rb, this spec will fail:<br />

Diff:<br />

@@ -1,10 +1,2 @@<br />

-<br />

-<br />

- <br />

- [timestamp]<br />

- 1<br />

- Ticketee<br />

- [timestamp]<br />

- <br />

-<br />

+<br />

...<br />

2 examples, 1 failure<br />

The diff here shows that the expected XML is nowhere to be found in the response,<br />

and instead you’re getting back a final line of absolutely nothing. This is because your<br />

Api::V1::BaseController doesn’t yet respond to XML requests. So now with a failing<br />

test you can go right ahead and change this controller to fix it. To make your API serve<br />

XML requests, you’ll change this line in app/controllers/api/v1/base_controller.rb<br />

respond_to :json<br />

to this:<br />

respond_to :json, :xml<br />

This simple little change will now make your spec pass, which you can see by running<br />

bin/rspec spec/api/v1/projects_spec.rb:<br />

2 examples, 0 failures<br />

Apologies if something harder was expected, but it really is this simple in Rails. You’ve<br />

only changed the API controller and spec, and it’s all contained in itself, but even so<br />

it’s still a good habit to run all the features and specs to make sure everything is fine:<br />

61 scenarios (61 passed)<br />

726 steps (726 passed)<br />

# and<br />

36 examples, 0 failures, 12 pending<br />

Green is good. Commit this change:<br />

git add .<br />

git commit -m "Support XML & JSON with /api/v1/projects"<br />

git push<br />

Now that you’ve got your first action of your API responding to both XML and JSON,<br />

why don’t you make some more actions, like the create action for creating projects in<br />

Ticketee?<br />

359

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

Saved successfully!

Ooh no, something went wrong!