Search code examples
rubyunit-testingmockingblockrr

Unit Testing Ruby Blocks by Mocking with rr (was flexmock)


How do I unit test the following:

  def update_config
    store = YAML::Store.new('config.yaml')
    store.transaction do
      store['A'] = 'a'
    end
  end

Here is my start:

  def test_yaml_store
    mock_store = flexmock('store')
    mock_store
      .should_receive(:transaction)
      .once
    flexmock(YAML::Store).should_receive(:new).returns(mock_store)
    update_config()
  end

How do I test what is inside the block?

UPDATED

I have converted my test to spec and switched to rr mocking framework:

describe 'update_config' do
  it 'calls transaction' do
    stub(YAML::Store).new do |store|
      mock(store).transaction
    end
    update_config
  end
end

This will test the transaction was called. How do I test inside the block: store['A'] = 'a'?


Solution

  • You want to call yields:

    describe 'update_config' do
      it 'calls transaction which stores A = a' do
        stub(YAML::Store).new do |store|
          mock(store).transaction.yields
          mock(store).[]=('A', 'a')
        end
        update_config
      end
    end
    

    Check out this answer for a different approach to a related question. Hopefully the rr api documentation will improve.