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.

140 CHAPTER 7 Basic access control<br />

Dir[Rails.root + "factories/*.rb"].each do |file|<br />

require file<br />

end<br />

When the value of the email method is inside a block, it’s evaluated every time this<br />

factory is called and generates a new (hopefully random) email address.<br />

The next bit of code to write is in your spec and is the first example to ensure that<br />

users who are not admins (such as the user object) cannot access the new action. The<br />

code in the following listing should replace the placeholder "cannot access the new<br />

action" example you’ve already got.<br />

Listing 7.4 spec/controllers/projects_controller_spec.rb<br />

context "standard users" do<br />

it "cannot access the new action" do<br />

sign_in(:user, user)<br />

get :new<br />

response.should redirect_to(root_path)<br />

flash[:alert].should eql("You must be an admin to do that.")<br />

end<br />

end<br />

This spec is placed inside a context block because you’ll have specs for standard users<br />

later. context blocks function similarly to describe blocks; they’re mainly used to<br />

specify the context of an example rather than to describe what it does.<br />

On the first line of the example, you use the sign_in method, which is available in<br />

Devise, but the appropriate part isn’t yet included. This method takes two arguments:<br />

the scope and the resource. Because you have only one scope for Devise, you don’t<br />

have to worry about what this means right now. What you do care about is that this<br />

method will sign in a user.<br />

To add this method, you must include a module in your RSpec configuration: the<br />

Devise::TestHelpers module. Open spec/spec_helper.rb, and you’ll see the<br />

RSpec.configure block (comments stripped) shown in the following listing.<br />

Listing 7.5 spec/spec_helper.rb<br />

RSpec.configure do |config|<br />

config.mock_with :rspec<br />

end<br />

This configure method is responsible for setting up RSpec. To include the<br />

Devise::TestHelpers method, you could use it like this:<br />

RSpec.configure do |config|<br />

config.mock_with :rspec<br />

config.include Devise::TestHelpers<br />

end<br />

But you may want to rerun the RSpec generator to update your spec/spec_helper.rb<br />

file and its associates when you update RSpec. If this file is updated, you’ll lose your

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

Saved successfully!

Ooh no, something went wrong!