5kfxhg
Last Updated: February 25, 2016
·
3.163K
· nielsen
6a7c0d92f8bd76d56550bdc8ee1dd5f3

Dynamic RSpec Tests

Conversion is a hairy, scary monster

Because RSpec is primarily a DSL for describing expectations, you can instantiate tests on the fly. The use case where I found this helpful was around testing edge cases and boundary conditions for a time converter. (For functional tests, it behaves like tabular parameters in jBehave and data tables in Cucumber.)

I created a Hash of potential tests, and enumerated them: In the block, I fed in the values from the |k,v| to the test and generated 6 tests against the static convert method on the fly.

describe AmbiguousTime do
  times = { 43200 => '12:00PM',
            72000 => '8:00PM',
            84600 => '23:30PM',
            27000 => '7:30AM',
            55800 => '3:30PM',
            55800 => '3:30'  }

  times.each do |planned_output, input|
    it "should return #{planned_output} from #{input}" do
      actual_output = AmbiguousTime::convert(input)
      actual_output.should eql(planned_output)
    end
  end
end

N.B. There's a 'gotcha' in the "answer => question" setup; because Ruby freezes the keys of a Hash, you can't perform modification operations on them. So, the arrangement |output, input| takes that into account.

Say Thanks
Respond

1 Response
Add your response

3340
2aaae7041aca85da930bcaf14d6768d2

Nice one.

over 1 year ago ·