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.

Restricting write access<br />

This feature will pass whether the user has permission to create a ticket or not. You’re<br />

now basically in the same situation you faced with the Viewing Tickets feature: the feature<br />

would pass either way. So, just like before, you use RSpec to test that users can’t<br />

create a ticket if they don’t have permission to do so.<br />

8.5.2 Blocking creation<br />

Let’s write the specs to test that users with permission to view the project but without<br />

permission to create tickets can’t create tickets. Put the specs shown in the following<br />

listing in spec/controllers/tickets_controller_spec.rb inside the standard users context<br />

block so all the examples are grouped nicely.<br />

Listing 8.7 spec/controllers/tickets_controller_spec.rb<br />

context "with permission to view the project" do<br />

before do<br />

sign_in(:user, user)<br />

Permission.create!(:user => user, :thing => project, :action => "view")<br />

end<br />

def cannot_create_tickets!<br />

response.should redirect_to(project)<br />

flash[:alert].should eql("You cannot create tickets on this project.")<br />

end<br />

it "cannot begin to create a ticket" do<br />

get :new, :project_id => project.id<br />

cannot_create_tickets!<br />

end<br />

it "cannot create a ticket without permission" do<br />

post :create, :project_id => project.id<br />

cannot_create_tickets!<br />

end<br />

end<br />

You first set up the specs using a before, signing in as a user, and defining a permission<br />

for that user to view the project. Next, you define a method called cannot<br />

_create_tickets! asserting that unauthorized users should be redirected to the project<br />

and shown an alert stating they’re not allowed to create tickets. Rather than duplicating<br />

these two lines in each spec where you want to check that a user receives the<br />

correct message, you just call the cannot_create_tickets! method in that place. The<br />

two examples you just added ensure that unauthorized visitors to the new and create<br />

actions can’t create tickets.<br />

When you run this file with bin/rspec spec/controllers/tickets_controller<br />

_spec.rb, the specs fail, just as you might expect:<br />

Failure/Error: response.should redirect_to(project)<br />

Expected response to be a , but was <br />

187

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

Saved successfully!

Ooh no, something went wrong!