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.

Namespace routing<br />

The new RSpec method, before, takes a block of code that’s executed before every<br />

spec inside the current context or describe.<br />

You use the lengthy let(:user) block again, which is effectively the same as what<br />

you have in spec/controllers/projects_controller_spec.rb. Rather than duplicating the<br />

code inside this block, move it into a new file in your spec/support directory. Its job is<br />

to provide methods to help you seed your test data, so call it seed_helpers.rb. In this<br />

file, create a module called SeedHelpers, which contains a create_user! method that<br />

uses the code from the let. This file is shown in the following listing.<br />

Listing 7.17 spec/support/seed_helpers.rb<br />

module SeedHelpers<br />

def create_user!(attributes={})<br />

user = Factory(:user, attributes)<br />

user.confirm!<br />

user<br />

end<br />

end<br />

RSpec.configure do |config|<br />

config.include SeedHelpers<br />

end<br />

With this new spec/support/seed_helpers.rb file, you can now use create_user!<br />

rather than the three lines of code you’re currently using. Let’s change the<br />

let(:user) in spec/controllers/projects_controller_spec.rb to this:<br />

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

Ah, much better! Let’s also change it in the new spec/controllers/admin/users<br />

_controller_spec.rb file:<br />

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

When you run this spec file using bin/rspec spec/controllers/admin/users<br />

_controller_spec.rb, you see that there’s no route to the index action:<br />

1) Admin::UsersController regular users are not able to access the<br />

➥index action<br />

Failure/Error: get 'index'<br />

No route matches {:controller => "admin/users"}<br />

In fact, there’s no route to the controller at all! To define this route, open config/<br />

routes.rb and insert the following code before the final end in the file.<br />

Listing 7.18 config/routes.rb<br />

namespace :admin do<br />

resources :users<br />

end<br />

This code defines similar routes to the vanilla resources but nests them under an<br />

admin/ prefix. Additionally, the routing helpers for these routes have an admin part to<br />

149

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

Saved successfully!

Ooh no, something went wrong!