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.

32 CHAPTER 2 Testing saves your bacon<br />

When you run rspec spec, it passes. Now let’s change the spec first, as in the next<br />

listing.<br />

Listing 2.11 bacon/spec/bacon_spec.rb<br />

describe Bacon do<br />

it "is edible" do<br />

Bacon.new.edible?.should be_true<br />

end<br />

end<br />

In this code, you instantiate a new object of the class rather than using the Bacon class.<br />

When you run rspec spec, it breaks once again:<br />

NoMethodError in 'Bacon is edible'<br />

undefined method `edible?' for #<br />

If you remove the self. from the edible? method, your test will now pass, as in the<br />

following listing.<br />

Listing 2.12 Terminal<br />

$ rspec spec<br />

.<br />

1 example, 0 failures<br />

Now you can go about breaking your test once more by adding additional functionality:<br />

an expired! method, which will make your bacon inedible. This method sets an<br />

instance variable on the Bacon object called @expired to true, and you use it in your<br />

edible? method to check the bacon’s status.<br />

First you must test that this expired! method is going to actually do what you think<br />

it should do. Create another example in spec/bacon_spec.rb so that the whole file now<br />

looks like the following listing.<br />

Listing 2.13 bacon/spec/bacon_spec.rb<br />

require 'bacon'<br />

describe Bacon do<br />

it "is edible" do<br />

Bacon.new.edible?.should be_true<br />

end<br />

it "expired!" do<br />

bacon = Bacon.new<br />

bacon.expired!<br />

bacon.should be_expired<br />

end<br />

end<br />

When you find you’re repeating yourself, stop! You can see here that you’re defining a<br />

bacon variable to Bacon.new and that you’re also using Bacon.new in the first example.<br />

You shouldn’t be repeating yourself like that!

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

Saved successfully!

Ooh no, something went wrong!