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.

Managing states<br />

Now in this step definition you find the state by the name given to you by the step and<br />

then find the link using the “When I follow [x] within [y]” step provided by Capybara.<br />

When you run this feature again, you’re told that it can’t find the state element you’re<br />

referencing:<br />

And I follow "Make default" for the "New" state<br />

scope '//*[@id = 'state_1']' not found on page (Capybara::ElementNotFound)<br />

This is because you haven’t added the id attribute to your state li tags inside the app/<br />

views/admin/states/index.html.erb. You can do this now by changing the following<br />

line inside this view; while you’re here, also add the Make Default link:<br />

<br />

To this:<br />

<br />

<br />

<br />

<br />

When you run your feature again you’ll rightly be told that the make_default_admin<br />

_state_path method is undefined. This method should take you to the make_default<br />

action in the Admin::StatesController, much like edit_admin_state_path takes<br />

you to the edit action. You can define this method as a member route on your states<br />

resource. A member route provides the routing helpers and, more important, the<br />

route itself, to a custom controller action for a single instance of a resource. To define<br />

this, you change the resources :states line inside the admin namespace inside<br />

config/routes.rb to the following:<br />

resources :states do<br />

member do<br />

get :make_default<br />

end<br />

end<br />

Inside the member block here, you define that each state resource has a new action<br />

called make_default that can be accessed through a GET request. As stated previously,<br />

by defining the route in this fashion you also get the<br />

make_default_admin_state_path helper which you use in app/views/admin/states/<br />

index.html.erb. With this member route now defined, your feature will complain that<br />

it’s missing the make_default action:<br />

And I follow "Make default" for the "New" state<br />

The action 'make_default' could not be found for<br />

Admin::StatesController (AbstractController::ActionNotFound)<br />

The make_default action will be responsible for making the state you’ve selected the<br />

new default state, as well as setting the old default state to not be the default anymore.<br />

You can define this action inside app/controllers/admin/states_controller.rb, as shown<br />

in the following listing.<br />

275

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

Saved successfully!

Ooh no, something went wrong!