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.

Viewing projects<br />

If you run the Cucumber feature again, you get this error, which isn’t helpful at first<br />

glance:<br />

Showing /[path to ticketee]/app/views/projects/index.html.erb<br />

where line #5<br />

raised:<br />

You have a nil object when you didn't expect it!<br />

You might have expected an instance of Array.<br />

This error points at line 5 of your app/views/projects/index.html.erb file. From this<br />

you can determine that the error has something to do with the @projects variable.<br />

This variable isn’t yet been defined, and because there’s no each method on nil, you<br />

get this error. As mentioned in chapter 3, instance variables in Ruby return nil rather<br />

than raise an exception if they’re undefined. Watch out for this in Ruby—as seen<br />

here, it can sting you hard.<br />

To define this variable, open ProjectsController at app/controllers/<br />

projects_controller.rb and change the index method definition to look like the following<br />

listing.<br />

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

def index<br />

@projects = Project.all<br />

end<br />

By calling all on the Project model, you retrieve all the records from the database as<br />

Project objects, and they’re available as an Array-like object. Now that you’ve put all<br />

the pieces in place, you can run the feature with bin/cucumber features/<br />

viewing_projects.feature, and all the steps should pass:<br />

1 scenario (1 passed)<br />

4 steps (4 passed)<br />

The feature now passes. Is everything else still working, though? You can check by running<br />

rake cucumber:ok. At the bottom, you should see this:<br />

3 scenarios (3 passed)<br />

16 steps (16 passed)<br />

All of your scenarios and their steps are passing, meaning all of the functionality<br />

you’ve written so far is working as it should. Commit and push this using<br />

git add .<br />

git commit -m "Added the ability to view a list of all projects"<br />

git push<br />

The reading part of this CRUD resource is done! You’ve got the index and show<br />

actions for the ProjectsController behaving as they should. Now you can move on<br />

to updating.<br />

87

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

Saved successfully!

Ooh no, something went wrong!