2
votes

I'm using rspec 3.0.0.beta1. I have to test a method which yields self:

class Test
  def initialize
    yield self if block_given?
  end
end

This is a succesful test:

describe Test do
  context 'giving a block with one argument' do
    it 'yields self'
      expect { |b| described_class.new &b }.to yield_with_args described_class
    end
  end
end

But it only tests the object class, without testing the identity to self.

This is the closest (failing) test I wrote:

describe Test do
  context 'giving a block with one argument' do
    it 'yields itself'
      instance = nil
      expect { |b|
        instance = described_class.new &b
      }.to yield_with_args instance
    end
  end
end

It fails indeed, since that, at the time the last instance occurrence is evaluated it is nil, so it doesn't match with the instance inside the block evaluation.

1

1 Answers

5
votes

The yield matchers cannot be used directly in your situation. The simplest thing to do is a variation of your second code with a different matcher later.

describe Test do
  context 'giving a block with one argument' do
    it 'yields itself'
      yielded_instance = nil
      new_instance = described_class.new { |i| yielded_instance = i }
      expect(yielded_instance).to be new_instance
    end
  end
end