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.

The projects API<br />

You’re not going to be able to use this same before_filter for your API because the<br />

API doesn’t return flash messages. You have to return errors in a lovely little JSON or<br />

XML format. This particular error, for example, is “You must be an admin.” Also, redirection<br />

doesn’t make sense here, because it wouldn’t tell users why they were redirected.<br />

Therefore, you’ll implement a different authorize_admin! method in your<br />

Api::V1::BaseController instead. You’ll take the time, however, to write a test to<br />

check for this error occurring. Let’s open a new file at spec/api/v1/project<br />

_errors_spec.rb and add a test that if you attempt to make a POST request to api/v1/<br />

projects using a token for a user who’s not an admin, you get an error. Use the code<br />

from the following listing.<br />

Listing 13.11 spec/api/v1/project_errors_spec.rb<br />

require "spec_helper"<br />

describe "Project API errors", :type => :api do<br />

context "standard users" do<br />

let(:user) { create_user! }<br />

it "cannot create projects" do<br />

post "/api/v1/projects.json",<br />

:token => user.authentication_token,<br />

:project => {<br />

:name => "Ticketee"<br />

}<br />

error = { :error => "You must be an admin to do that." }<br />

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

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

Project.find_by_name("Ticketee").should be_nil<br />

end<br />

end<br />

end<br />

With this spec, you test that a normal user who’s using a valid authenticity token cannot<br />

create a project through the API because they’re not an admin. Instead, the API<br />

should return a response of “You must be an admin to do that.” This response should<br />

have a code of 401, indicating an Unauthorized response. When you run this spec<br />

using bin/rspec spec/api/v1/project_errors_spec.rb, it will not return the error<br />

as you expect:<br />

expected "{\"error\":\"You must be an admin to do that.\"}"<br />

got "{[project hash]}"<br />

To make this error happen, you’ll go into app/controllers/api/v1/base_controller.rb<br />

and underneath your authenticate_user method add the authorize_admin!<br />

method shown in the following listing.<br />

Listing 13.12 app/controllers/api/v1/base_controller.rb<br />

def authorize_admin!<br />

if !@current_user.admin?<br />

if !@current_user.admin?<br />

363

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

Saved successfully!

Ooh no, something went wrong!