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.

262 CHAPTER 10 Tracking state<br />

Listing 10.16 features/creating_comments.feature:26<br />

Scenario: Creating an invalid comment<br />

When I follow "Change a ticket's state"<br />

And I press "Create Comment"<br />

Then I should see "Comment has not been created."<br />

And I should see "Text can't be blank"<br />

This scenario tests that you’re shown the “Text can’t be blank” error when you don’t<br />

enter any text for your comment. In this scenario, you click the Create Comment button,<br />

which submits your form, which goes to the create action in Comments-<br />

Controller. This action looks like the following listing.<br />

Listing 10.17 app/controllers/comments_controller.rb<br />

def create<br />

@comment = @ticket.comments.build(params[:comment].merge(:user<br />

➥=> current_user))<br />

if @comment.save<br />

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

redirect_to [@ticket.project, @ticket]<br />

else<br />

flash[:alert] = "Comment has not been created."<br />

render :template => "tickets/show"<br />

end<br />

end<br />

As you can see from this action, when the comment fails validation (when @comment<br />

.save returns false), then it rerenders the app/views/tickets/show.html.erb template.<br />

The problem with this is that, by rerendering this template, it calls the following line<br />

in the template:<br />

<br />

This inevitably leads you right back to app/views/comments/_form.html.erb, the<br />

source of the problem. Therefore, you can determine that you need to set up the<br />

@states variable during the “failed save” part of your action, and the best place for<br />

this is right after the else so that this part ends up looking like the following listing.<br />

Listing 10.18 app/controllers/comments_controller.rb<br />

else<br />

@states = State.all<br />

flash[:alert] = "Comment has not been created."<br />

render :template => "tickets/show"<br />

end<br />

Now that you’re correctly initializing your @states variable, this scenario will pass.<br />

Let’s run the whole feature now using bin/cucumber features/creating_comments<br />

.feature:<br />

3 scenarios (3 passed)<br />

39 steps (39 passed)

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

Saved successfully!

Ooh no, something went wrong!