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.

to this:<br />

The projects API<br />

before_filter :find_project, :only => [:show, :update]<br />

Now in the update action you’ll have a project that you can work with because this<br />

before_filter will find it for you. Next, you’ll write this action into the controller<br />

using the code from the following listing.<br />

Listing 13.18 app/controllers/api/v1/projects_controller.rb<br />

def update<br />

@project.update_attributes(params[:project])<br />

respond_with(@project)<br />

end<br />

Well isn’t this quite a difference from your standard update actions? You only need to<br />

call update_attributes here, which will save the object and return a valid object in<br />

the format that you’ve asked for. If this object fails validation, the status code returned<br />

by respond_with will be 422, which represents an Unprocessable Entity, and the body<br />

will contain only the validation errors that occurred. If the object is valid,<br />

respond_with will return a 200 status code, but an empty response. This is because<br />

the client should be aware of what changes it has made to the object, and so there’s no<br />

need to send back the object.<br />

So which is it? Does the update action work and return the 200 status code you<br />

want, or does it break? It’s easy to find out by running bin/rspec spec/api/v1/<br />

projects_spec.rb:<br />

5 examples, 0 failures<br />

All working, good stuff. You’ve now got a check that the update action responds correctly<br />

when a valid object is given, but what if invalid parameters are given instead?<br />

Well, the action should return that 422 response mentioned earlier. Although this is<br />

testing the already extensively tested 13 Rails behavior, you’re making sure that this<br />

action always does what you think it should. No misbehaving allowed! You’ll quickly<br />

whip up a spec for this, placing it right underneath the previous example, “successful<br />

JSON” that you wrote in spec/api/v1/projects_spec.rb. The code for it is shown in the<br />

following listing.<br />

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

it "unsuccessful JSON" do<br />

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

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

:project => {<br />

:name => ""<br />

}<br />

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

13 It’s tested within Rails itself.<br />

371

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

Saved successfully!

Ooh no, something went wrong!