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.

532 CHAPTER 18 Rack-based applications<br />

Because you’re not too concerned with what happens if an invalid<br />

params[:project_id] or user token is passed through at the moment, you’ll fix those<br />

up after you’ve got this first test passing. With the project now found, you should be<br />

able to display a list of tickets in JSON form in your call method. Let’s change your<br />

root route to return a list of JSON-ified tickets for this project:<br />

get '/' do<br />

@project.tickets.to_json<br />

end<br />

Now your root route should respond with the list of tickets required to have your test<br />

pass. Let’s see if this is the case by running bin/rspec spec/api/v3/json/<br />

tickets_spec.rb:<br />

1 example, 0 failures<br />

Great, this spec is now passing, which means that your Rack application is now serving<br />

a base for version 3 of your API. By making this a Rack application, you can serve<br />

requests in a more lightweight fashion than you could within Rails.<br />

But you don’t have basic error checking in place yet if a user isn’t found matching<br />

a token or if a person can’t find a project. So before you move on, let’s quickly add<br />

tests for these two issues.<br />

18.3.4 Basic error checking<br />

You’ll open spec/api/v3/json/tickets_spec.rb and add two tests inside the describe<br />

block in a new context block, as shown in the following listing.<br />

Listing 18.9 spec/api/v3/json/tickets_spec.rb<br />

context "unsuccessful requests" do<br />

it "doesn't pass through a token" do<br />

get url<br />

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

last_response.body.should eql("Token is invalid.")<br />

end<br />

it "cannot access a project that they don't have permission to" do<br />

user.permissions.delete_all<br />

get url, :token => token<br />

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

end<br />

end<br />

In the first test you make a request without passing through a token, which should<br />

result in a 401 (unauthorized) status and a message telling you the “Token is invalid.”<br />

In the second test, you use the delete_all association method to remove all permissions<br />

for the user and then attempt to request tickets in a project that the user no longer<br />

has access to. This should result in the response being a 404 response, which<br />

means your API will deny all knowledge of that project and its tickets.

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

Saved successfully!

Ooh no, something went wrong!