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.

372 CHAPTER 13 Designing an API<br />

@project.reload<br />

@project.name.should eql("Ticketee")<br />

errors = { :name => ["can't be blank"]}<br />

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

end<br />

In this example, you attempt to set the project’s name to a blank string, which should<br />

result in the 422 error you want to see. After you reload the project, the name should<br />

be the same. You should then get the 422 error as the response.<br />

A quick run of bin/rspec spec/api/v1/projects_spec.rb should let you know if<br />

this is working:<br />

7 examples, 0 failures<br />

Indeed it is! Is everything else working? A run of rake spec will let you know:<br />

51 examples, 0 failures, 19 pending<br />

“51 examples, 0 failures” is exactly what you like to see. That means that your update<br />

action is all wrapped up, and now it’s time for a commit:<br />

git add .<br />

git commit -m "Implement update action for projects API"<br />

git push<br />

You’ve now got three fourths of the CRUD of this API. You’re able to create, read, and<br />

update project resources. With updating, clients authorized with an admin’s token<br />

can send through updates to the project resource, which will update the information<br />

in the application. The one remaining action you’ve got to implement is the destroy<br />

action, for making projects go bye-bye. You’re almost home!<br />

13.1.11 Exterminate!<br />

You need to create the destroy action, which allows admins of Ticketee to delete projects<br />

through the API. To do this, API clients need to make a DELETE request to /api/<br />

v1/projects/1.json or /api/v1/projects/1.xml. Upon making this request, the specified<br />

project will be deleted—gone forever, exterminated!<br />

You’ll write the final example in the spec/v1/api/projects_spec.rb to make sure<br />

that people are able to delete projects using this route. You’ll use the code from the<br />

following listing to do this.<br />

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

context "deleting a project" do<br />

before do<br />

user.admin = true<br />

user.save<br />

end<br />

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

it "JSON" do<br />

delete "#{url}.json", :token => token

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

Saved successfully!

Ooh no, something went wrong!