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.

362 CHAPTER 13 Designing an API<br />

This should be all that you need in order to get your spec to pass, so let’s see what<br />

happens when you run bin/rspec spec/api/v1/projects_spec.rb:<br />

3 examples, 0 failures<br />

Great! Now you need to write a test to check that when you attempt to pass through a<br />

project with no name you’re given a 422 status code and an error along with it, indicating<br />

that the project wasn’t created due to those errors. Directly underneath the<br />

previous test in spec/api/v1/projects_spec.rb, you’ll add this test shown in the following<br />

listing.<br />

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

it "unsuccessful JSON" do<br />

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

:project => {}<br />

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

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

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

end<br />

Naughty you, writing the test after the code is already there, but you can get away with<br />

it once. Let’s run the spec and see how it goes now:<br />

4 examples, 0 failures<br />

Great success! With this URL working for valid and non-valid projects appropriately,<br />

you are now providing a way for your users to create a project through the API, and so<br />

it’s time to make a commit:<br />

git add .<br />

git commit -m "Added API to create projects"<br />

git push<br />

Your next task is to restrict this action to only the admins of your application, as in the<br />

real ProjectsController controller. You want to limit the number of people who can<br />

change the projects to a select few who know what they’re doing.<br />

13.1.7 Restricting access to only admins<br />

In app/controllers/projects_controller.rb you’ve got this line, which restricts some<br />

actions to only admins:<br />

before_filter :authorize_admin!, :except => [:index, :show]<br />

As it says on the line, every action other than index or show has this filter run before<br />

it. This filter is defined in app/controllers/application_controller.rb like this:<br />

def authorize_admin!<br />

authenticate_user!<br />

unless current_user.admin?<br />

flash[:alert] = "You must be an admin to do that."<br />

redirect_to root_path<br />

end<br />

end

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

Saved successfully!

Ooh no, something went wrong!