views:

128

answers:

1

Hi,

I'm using shoulda with Ruby on Rails, and I have the following test cases:

class BirdTest < Test::Unit::TestCase

    context "An eagle" do
      setup do
        @eagle = Eagle.new
      end
      should "be able to fly" do
        assert_true  @eagle.can_fly?
      end
    end

    context "A Crane" do
      setup do
        @crane = Crane.new
      end
      should "be able to fly" do
        assert_true  @crane.can_fly?
      end
    end

    context "A Sparrow" do
      setup do
        @sparrow = Sparrow.new
      end
      should "be able to fly" do
        assert_true  @sparrow.can_fly?
      end
    end

end

It works well but I hate the duplicate code I've written here. So I'm hoping to write a test case like the following. This test case should be run several times, and each time the value of some_bird is set to a different one. Is that doable?

class BirdTest < Test::Unit::TestCase

    context "Birds" do
      setup do
        @flying_bird = some_bird
      end
      should "be able to fly" do
        assert_true  @flying_bird.can_fly?
      end
    end

end

Thanks,

Bryan

+2  A: 

You could try something like this for your current example

class BirdTest < Test::Unit::TestCase
  context "Birds" do
    [Crane, Sparrow, Eagle].each do |bird|
      context "A #{bird.name}" do
        should "be able to fly" do
          this_bird = bird.new
          assert this_bird.can_fly?
        end
      end
    end
  end
end
nowk
Fantastic! This is exactly what I want. Thank you!
Bryan