views:

37

answers:

1

I was working with the lotrepls Ruby interpreter, and I want like to write tests in the interpreter that I can then write Ruby code to pass. In Python, I can write doctests and then write code to pass the doctests. For example:

>>> b  
1

This tests that b=1, and entering b=1 will get this doctest to pass.

Is there a similar way to write tests in a Ruby interpreter, execute them, write code to pass the tests, and then execute the test again? Is there a Ruby doctest equivalent? For my application, I will execute tests and code in a hosted interpreter like lotrepls rather than install something on my local machine.

+1  A: 

There's RubyDocTest, but I'd encourage you to look at something like RSpec or another modern BDD/TDD framework.

It's pretty easy to write tests there too, and you get access to complex and/or custom assertions that you can't really get in a doctest. For instance, here's a simple set of tests for a baseball scoring app:

describe BaseballScorer do
  before :each do
    @s = Scorer.new(Game.new)
  end

  it "should score a 0-0 game when no runs are hit" do
    @s.home.score.should == @s.away.score.should == @s.total_runs
  end

  it "should record runs that are hit" do
    @s.game.run_hit(:away)
    @s.away.runs.should == @s.away.score.should == 1
  end

  # ...
John Feminella
Thanks John. Can I execute spec in an interactive session without reading in specs from a file? Can I enter in the code above in an IRB session and then run something like:>> spec BaseballScorer #Rather than >> spec BaseballScorer.rb
Chris
Specs aren't associated with particular classes, per se. That is instead of `describe BaseballScorer`, I could have written `describe "Our baseball scoring algorithm"`. You can run the specs in a particular file with a SpecRunner; if you instantiate one of those, then you can run the tests. So the CLI interface is a little harder than a doctest would be. But you can run a Rake task to just run your specs, if that helps.
John Feminella
Thanks John. What is the simplest way to instantiate a SpecRunner instance and pass specs into it?
Chris