Is there an equivalent in RSpec to Cucumber's "Scenarios" or am I using RSpec the wrong way?
Try the following approach. I like the way it turned out.
describe StateDateMethods do
before :each do
@product = OpenStruct.new
@product.extend StateDateMethods
end
def parse_date(unparsed_date_value)
unless unparsed_date_value.nil?
DateTime.strptime(unparsed_date_value, '%m/%d/%Y')
end
end
context '#pre_order?' do
examples = [
# [visible_on, pre_order_on, for_sale_on] => method_result
{ :inputs => [nil, nil, nil], :expected => false },
{ :inputs => ['1/1/2001', nil, nil], :expected => false },
{ :inputs => ['1/1/2001', '1/1/2001', nil], :expected => true },
{ :inputs => ['1/1/2001', '1/2/2001', nil], :expected => true },
{ :inputs => ['1/1/2001', '1/1/2001', '1/2/2001'], :expected => false },
{ :inputs => ['1/1/2001', '1/1/2001', '1/1/3001'], :expected => true },
{ :inputs => ['1/1/2001', '1/1/3001', '1/2/3001'], :expected => false },
{ :inputs => ['1/1/3001', '1/1/3001', '1/2/3001'], :expected => false },
{ :inputs => ['1/1/2001', nil, '1/1/2001'], :expected => false },
{ :inputs => ['1/1/2001', nil, '1/1/3001'], :expected => false }
]
examples.each do |example|
inputs = example[:inputs]
it "should return #{example[:expected].inspect} when visible_on == #{inputs[0].inspect}, pre_order_on == #{inputs[1].inspect}, for_sale_on == #{inputs[2].inspect}" do
@product.visible_on = parse_date(inputs[0])
@product.pre_order_on = parse_date(inputs[1])
@product.for_sale_on = parse_date(inputs[2])
@product.pre_order?.should == example[:expected]
end
end
end
end
I think this gives the best of both worlds, because it keeps me from repeating myself, and it creates a different test for each condition.
Here's what a failure looks like:
....F.....
Failures:
1) StateDateMethods#pre_order? should return false when visible_on == "1/1/2001", pre_order_on == "1/1/2001", for_sale_on == "1/2/2001"
Failure/Error: @product.pre_order?.should == example[:expected]
expected: false
got: true (using ==)
# ./spec_no_rails/state_date_methods_spec.rb:40:in `block (4 levels) in <top (required)>'
Finished in 0.38933 seconds
10 examples, 1 failure
Failed examples:
rspec ./spec_no_rails/state_date_methods_spec.rb:35 # StateDateMethods#pre_order? should return false when visible_on == "1/1/2001", pre_order_on == "1/1/2001", for_sale_on == "1/2/2001"
And here's what all green looks like:
..........
Finished in 0.3889 seconds
10 examples, 0 failures
I give an example appropriate for RSpec in the question RSpec Scenario Outlines: Multiple Test Cases. I give one possible solution, but please let me know if you find a better one.