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.

Restricting actions to admins only<br />

projects_controller_spec.rb, and add a let inside the describe so the top of the spec<br />

looks like the following listing.<br />

describe ProjectsController do<br />

let(:user) do<br />

user = Factory(:user)<br />

user.confirm!<br />

user<br />

end<br />

context "standard users" do<br />

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

sign_in(:user, user)<br />

end<br />

end<br />

...<br />

end<br />

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

Here you use a multilined block for the let method. This method defines a user<br />

method, which returns a newly created and confirmed user. You create this user using<br />

Factory Girl.<br />

You then use this object in your test to sign in as that user. The benefit of using let<br />

over defining an instance variable in a before block is that the let code is called only<br />

when it’s referenced, whereas all the code in a before is evaluated regardless. This is<br />

helpful if some of your tests don’t need a User object.<br />

Underneath the let, you add a short placeholder test that signs in as the user,<br />

attempting to use the userlet method. With this test, the let block is called, and you<br />

should get an error when you run this spec using bin/rspec spec/controllers/<br />

projects _controller_spec.rb:<br />

Not registered: user (ArgumentError)<br />

Therefore, you should create a user factory that creates a user object with a random<br />

email address (because you may wish to create more than one user at a time using this<br />

factory), and the password should default to password. Define this factory in a new file<br />

called factories/user_factory.rb:<br />

Factory.define :user do |user|<br />

user.sequence(:email) { |n| "user#{n}@ticketee.com" }<br />

user.password "password"<br />

user.password_confirmation "password"<br />

end<br />

In this factory, you use the sequence method provided by Factory Girl, which passes a<br />

unique number to the block and makes your user’s email addresses unique.<br />

The files within the factories directory aren’t yet required by RSpec, so their factories<br />

aren’t available for you. To make RSpec load them, create a new file at spec/support<br />

/factories.rb and put this content in it:<br />

139

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

Saved successfully!

Ooh no, something went wrong!