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.

30 CHAPTER 2 Testing saves your bacon<br />

generate a bacon directory if it doesn’t already exist, and then generate in that directory<br />

a spec directory.<br />

Inside the spec directory, create a file called bacon_spec.rb. This is the file you use<br />

to test your currently nonexistent Bacon class. Put the code from the following listing<br />

in spec/bacon_spec.rb.<br />

describe Bacon do<br />

it "is edible" do<br />

Bacon.edible?.should be_true<br />

end<br />

end<br />

You describe the (undefined) Bacon class and write an example for it, declaring that<br />

Bacon is edible. The describe block contains tests (examples) that describe the<br />

behavior of bacon. In this example, whenever you call edible? on Bacon, the result<br />

should be true. should serves a similar purpose to assert, which is to assert that its<br />

object matches the arguments passed to it. If the outcome is not what you say it should<br />

be, then RSpec raises an error and goes no further with that spec.<br />

To run the spec, you run rspec spec in a terminal in the root of your bacon directory.<br />

You specify the spec directory as the first argument of this command so RSpec<br />

will run all the tests within that directory. This command can also take files as its arguments<br />

if you want to run tests only from those files.<br />

When you run this spec, you get an uninitialized constant Object::Bacon<br />

error, because you haven’t yet defined your Bacon constant. To define it, create<br />

another directory inside your Bacon project folder called lib, and inside this directory,<br />

create a file called bacon.rb. This is the file where you define the Bacon constant, a<br />

class, as in the following listing.<br />

class Bacon<br />

end<br />

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

Listing 2.7 bacon/lib/bacon.rb<br />

You can now require this file in spec/bacon_spec.rb by placing the following line at the<br />

top of the file:<br />

require 'bacon'<br />

When you run your spec again, because you told it to load bacon, RSpec has added the<br />

lib directory on the same level as the spec directory to Ruby’s load path, and so it will<br />

find the lib/bacon.rb for your require. By requiring the lib/bacon.rb file, you ensure<br />

the Bacon constant is defined. The next time you run it, you get an undefined method<br />

for your new constant:<br />

1) Bacon is edible<br />

Failure/Error: Bacon.edible?.should be_true

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

Saved successfully!

Ooh no, something went wrong!