Wednesday, April 26, 2006

RSpec for checkr part 1

To try to learn a bit more about RSpec, I've decided to write an rspec file for checkr. I learn best by doing, and this seemed like a good way to do something worthwhile. Apologies in advance for any mangled terminology, I'm just getting started with this stuff. Please feel free to correct me in a comment. I'll update this post as appropriate.

I decided to start small. So I wrote a simple test script and used the test2rspec tool to convert it.

class TestFoo < Test::Unit::TestCase
  def test_bar
    foo =
    assert_equal true,


context "" do
  specify "Bar" do
    foo = true

The output changed a little bit too:

$ ruby test_foo.rb
Loaded suite test_foo
Finished in 0.000646 seconds.

1 tests, 1 assertions, 0 failures, 0 errors


$ spec rspec_foo.rb
Finished in 0.000337 seconds

1 context, 1 specification, 0 failures

A useful bit of functionality is the ability to print more verbose output. It's not terribly interesting yet though, so let me play with the rspec file a bit before I show it to you.

In the first line of the rspec file, there's a pair of quotation marks right after the context. These are a place holder for the string I want to use to identify this context. On the next line, "Bar" is given as an identifying string for the specification we're working on (this all sounds like a spec not a test suite, doesn't it -- it's intentional). Let's make these strings a bit more meaningful, shall we:

context "Simple Case" do
  specify "Bar is true" do

Now, when I do spec -v rspec_foo.rb, the output looks a little more meaningful:

Simple Case
- Bar is true

Finished in 0.00054 seconds

1 context, 1 specification, 0 failures

What will this look like when it fails? Let's add a failing specification and find out:

  specify "Bar is false" do
    foo = false

Which generates output like this (slightly edited for the faint of heart):

Simple Case
- Bar is true
- Bar is false (FAILED - 1)

 should equal  (Spec::Api::ExpectationNotMetError)
./rspec_foo.rb:12:in `Bar is false'

[most of a stack trace deleted]

Finished in 0.000943 seconds

1 context, 2 specifications, 1 failure

Well, raising an exception and having multiple lines of stacktrace thrown onto my terminal isn't really what I'd hoped for. I'm at the end of space for a blog post and time on the bus though, so I'll see about cleaning this up on tomorrow's ride home.


Sean said...

BDD has a lot to offer in terms of keeping what is good from the best TDD and dropping the linguistic baggage that makes TDD so hard to get right.

I think we should seriously consider changing checkr over to rspec completely.

Eric Hodel said...

With luck we'll get unit_diff and friends working with RSpec this weekend provided Steven Baker can make it down to mind camp.