jpw
jpw

Reputation: 19247

rails rspec, any way to handle multiple 'should' for the same example via a block?

Suppose the model method foo() returns an array [true, false, 'unable to create widget']

Is there a way to write an rspec example that passes that array as a block that verifies [0] = true, [1] = false, and [2] matches a regex like /

Currently, I do it like:

result = p.foo
result[2].should match(/unable/i)
result[0].should == true
result[1].should == false

I can't quite get my head around how that might be doable with a block?

Upvotes: 0

Views: 99

Answers (2)

kiddorails
kiddorails

Reputation: 13014

Do you mean that your result is an array and you have to iterate over to test it's various cases?

Then, you can do that by following, right:

result = p.foo
result.each_with_index do |value, index|
  case index
  when 0 then value.should == true
  when 1 then value.should == false
  when 2 then value.shoud match(/unable/i)
  end 
end

Upvotes: 0

luacassus
luacassus

Reputation: 6720

It would be slightly over engineered but try to run this spec with --format documentation. You will see a very nice specdocs for this method ;)

describe '#some_method' do
  describe 'result' do
    let(:result) { subject.some_method }
    subject { result }

    it { should be_an_instance_of(Array) }

    describe 'first returned value' do
      subject { result.first }
      it { should be_false }
    end

    describe 'second returned value' do
      subject { result.second }
      it { should be_true }
    end

    describe 'third returned value' do
      subject { result.third }
      it { should == 'some value' }
    end
  end
end

Upvotes: 1

Related Questions