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.

First steps<br />

The render method in this variation renders the app/views/projects/_form.html.erb<br />

partial at this location.<br />

Now, running rake cucumber:ok once more, you can see that your feature is one<br />

step closer to finishing: the field is filled in. How did Capybara know where to find the<br />

correct field to fill in? Simple. When you defined the field inside app/views/projects/<br />

_form.html.erb, you used the syntax shown in the following listing.<br />

<br />

<br />

Capybara finds the label containing the "Name" text you ask for in your scenario and<br />

fills out the corresponding field. Capybara has a number of ways to locate a field, such<br />

as by the name of the corresponding label, the id attribute of the field, or the name<br />

attribute. The last two look like this:<br />

When I fill in "project_name" with "TextMate 2"<br />

# or<br />

When I fill in "project[name]" with "TextMate 2"<br />

These aren’t human friendly ways to find a field, so let’s use "Name" instead.<br />

When you run the feature again with rake cucumber:ok, you get this error:<br />

And I press "Create Project"<br />

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

The feature now complains of a missing action called create. To define this action,<br />

you define the create method underneath the new method in the Projects-<br />

Controller, as in the following listing.<br />

def create<br />

@project = Project.new(params[:project])<br />

@project.save<br />

flash[:notice] = "Project has been created."<br />

redirect_to @project<br />

end<br />

The new method takes the argument params, which is available inside controller methods<br />

and returns the parameters passed to the action, such as those from the form, as a<br />

HashWithIndifferentAccess object. These are different from normal Hash objects,<br />

because you can reference a String key by using a matching Symbol and vice versa. In<br />

this case, the params hash is<br />

{<br />

Listing 3.16 app/views/projects/_form.html.erb<br />

Listing 3.17 app/controllers/projects_controller.rb<br />

"commit" => "Create Project",<br />

"action" => "create",<br />

"project" => {<br />

"name" => "TextMate 2"<br />

67

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

Saved successfully!

Ooh no, something went wrong!