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.

294 CHAPTER 11 Tagging<br />

11.2.2 Fixing the CommentsController spec<br />

The CommentsController spec is failing with this error:<br />

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

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

The error occurred while evaluating nil.split<br />

# ./app/models/ticket.rb:16:in `tag!'<br />

# ./app/controllers/comments_controller.rb:12:in `create'<br />

Ah, it seems to be from within the tag! method from the Ticket model. The sixteenth<br />

line of this model is<br />

tags = tags.split(" ").map do |tag|<br />

It’s the calling of tags.split that is making the spec fail, but why? tags comes from<br />

the argument passed to this method from the CommentsController’s create action by<br />

this line:<br />

@ticket.tag!(params[:tags])<br />

You’d get this error if params[:tags] was ever nil, because you cannot call split on<br />

nil. Why is it nil in your controller spec, though? It’s because you’re not sending it<br />

through with the other parameters in your spec:<br />

post :create, { :comment => { :text => "Hacked!",<br />

:state_id => state.id },<br />

:ticket_id => ticket.id }<br />

You can solve this problem in one of two ways. The first way is to check that<br />

params[:tags] is not nil before calling the tag! method by adding code to the<br />

CommentsController, or better still, by adding code to the tag! method in the Ticket<br />

model. The second way is to make the controller spec accurately reflect reality.<br />

Because the Tags field is always going to be on the comments page, its value will be<br />

set to an empty string if it is left as-is. The second fix is therefore better, because it<br />

fixes the problem rather than compensating for an issue that will only happen in your<br />

tests. You can change the post method in the test in spec/controllers/<br />

comments_controller_spec.rb to this:<br />

post :create, { :tags => "",<br />

:comment => { :text => "Hacked!",<br />

:state_id => state.id },<br />

:ticket_id => ticket.id }<br />

Due to this small change, all your specs will be passing when you run rake spec again:<br />

27 examples, 0 failures, 10 pending<br />

With all the specs and features passing, it’s commit time! In this section, you’ve created<br />

a way for your users to add more tags to a ticket when they add a comment, which<br />

allows your users to easily organize tickets into relevant groups. Let’s commit this<br />

change now:

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

Saved successfully!

Ooh no, something went wrong!