Understanding Failure

To try your specs, run the rspec command from your project directory. RSpec will look inside the spec subdirectory for files named «something»_spec.rb and run them:

 $ ​​rspec
 F
 
 Failures:
 
  1) An ideal sandwich is delicious
  Failure/Error: sandwich = Sandwich.new(’delicious’, [])
 
  NameError:
  uninitialized constant Sandwich
  # ./spec/sandwich_spec.rb:4:in ‘block (2 levels) in <top (required)>’
 
 Finished in 0.00076 seconds (files took 0.08517 seconds to load)
 1 example, 1 failure
 
 Failed examples:
 
 rspec ./spec/sandwich_spec.rb:3 # An ideal sandwich is delicious

RSpec gives us a detailed report showing which spec failed, the line of code where the error occurred, and a description of the problem.

Additionally, the output is in color. RSpec uses color to emphasize different parts of the output:

  • Passing specs are green.
  • Failing specs, and failure details, are red.
  • Example descriptions and structural text are black.
  • Extra details such as stack traces are blue.
  • Pending specs (which we’ll see later in Marking Work in Progress) are yellow.

It’s a tremendous productivity boost to find what you’re looking for in the output before you’ve even read it. In Chapter 2, From Writing Specs to Running Them, we’ll see how to view our spec output in different formats.

Starting with a failing spec, as you’ve done here, is the first step of the Red/Green/Refactor development practice essential to TDD and BDD.[11] With this workflow, you’ll make sure each example catches failing or missing code before you implement the behavior you’re testing.

The next step after writing a failing spec is to make it pass. For this example, all you have to do is add the following line at the top of the file:

 Sandwich = Struct.new(​:taste​, ​:toppings​)

Here, you’ve defined a Sandwich struct with two fields, which is all your specs need in order to pass. Usually, you’d put this kind of implementation logic into a separate file, typically in the lib directory. For this simple example, it’s fine to define it directly in the spec file.

Now, when you rerun your specs, they’ll pass:

 $ ​​rspec
 .
 
 Finished in 0.00101 seconds (files took 0.08408 seconds to load)
 1 example, 0 failures

The three methods you’ve used in your spec—describe, it, and expect—are the core APIs of RSpec. You can go a long way with RSpec using just these pieces without any other embellishment.

That said, we can’t resist showing you a few more things.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset