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.

370 CHAPTER 13 Designing an API<br />

13.1.10 Updating a project<br />

To update a project in the API, people will need to make a POST request to the /api/<br />

v1/projects/:id URL with the project’s new information contained in a params[:project]<br />

hash. Simple, really.<br />

To test that this action works correctly, you’ll add yet another spec to spec/api/v1/<br />

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

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

context "updating 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 "successful JSON" do<br />

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

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

:project => {<br />

:name => "Not Ticketee"<br />

}<br />

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

@project.reload<br />

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

last_response.body.should eql("{}")<br />

end<br />

end<br />

At the top of this new context block, you’ve defined that the user is an admin again.<br />

You could wrap the create and update tests within another context that sets this flag<br />

too, but you’ll do it this way for now.<br />

You need to make a put request to this action for Rails to accept it, and you can do<br />

that by using the put method B. Along with this request, you send the token and<br />

project parameters. The project parameter contains a new name for this project.<br />

Because it’s a valid (non-blank) name, the response’s status code will be 200, but the<br />

response will be an empty hash indicating no errors. This doesn’t return an updated<br />

object, because what’s the point? The client should be aware of the updates that have<br />

occurred, given it triggered them!<br />

At the end of this spec, you use the reload method to find this object again from<br />

the database. This is because the object that the spec is working with will be a completely<br />

different Ruby object from the one in the update action in the controller. By<br />

calling reload, Rails will fetch the data for this object again from the database and<br />

update the object in the process.<br />

To begin writing this action in Api::V1::ProjectsController, you’re going to<br />

need to first modify the before_filter :find_project line to include the update<br />

action, changing it from this<br />

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

B put request

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

Saved successfully!

Ooh no, something went wrong!