27.02.2013 Views

Rails%203%20In%20Action

Rails%203%20In%20Action

Rails%203%20In%20Action

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

42 CHAPTER 2 Testing saves your bacon<br />

When /^I take out (\d+)$/ do |amount|<br />

@account.balance -= amount.to_i<br />

end<br />

That makes this third step pass, because you’re subtracting a Fixnum from a Fixnum.<br />

When you run this feature, you’ll see that this step is definitely passing and the final<br />

step is now pending:<br />

Scenario: Taking out money<br />

Given I have an account<br />

And it has a balance of 100<br />

When I take out 10<br />

Then my balance should be 90<br />

TODO (Cucumber::Pending)<br />

This final step asserts that your account balance is now 90. You can implement it in<br />

features/step_definitions/account_steps.rb, as shown in the following listing.<br />

Then /^my balance should be (\d+)$/ do |amount|<br />

@account.balance.should eql(amount.to_i)<br />

end<br />

Here you must coerce the amount variable into a Fixnum again so you’re comparing a<br />

Fixnum with a Fixnum. With this fourth and final step implemented, your entire scenario<br />

(which also means your entire feature) passes:<br />

Scenario: Taking out money<br />

Given I have an account<br />

And it has a balance of 100<br />

When I take out 10<br />

Then my balance should be 90<br />

1 scenario (1 passed)<br />

4 steps (4 passed)<br />

As you can see from this example, Cucumber allows you to write tests for your code in<br />

syntax that can be understood by developers, clients, and parsers alike. You’ll see a lot<br />

more of Cucumber when you use it in building your next Ruby on Rails application.<br />

2.4 Summary<br />

Listing 2.32 features/step_definitions/account_steps.rb<br />

Listing 2.33 features/step_definitions/account_steps.rb<br />

This chapter demonstrated how to apply TDD and BDD principles to test some rudimentary<br />

code. You can (and should!) apply these principles to all code you write,<br />

because testing the code ensures it’s maintainable from now into the future. You don’t<br />

have to use the gems shown in this chapter to test your Rails application; they are just<br />

preferred by a large portion of the community.<br />

You’ll apply what you learned in this chapter to building a Rails application from<br />

scratch in upcoming chapters. You’ll use Cucumber from the outset by developing

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

Saved successfully!

Ooh no, something went wrong!