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

倾然丶 夕夏残阳落幕 提交于 2019-12-01 14:05:26

First, you can write this a little simpler -- your test using RR isn't a direct port of your test using FlexMock. Second, you're not testing what happens within the block at all so your test is incomplete. Try this instead:

describe '#update_config' do
  it 'makes a YAML::Store and stores A in it within a transaction' do
    mock_store = {}
    mock(mock_store).transaction.yields
    mock(YAML::Store).new { mock_store }
    update_config
    expect(mock_store['A']).to eq 'a'
  end
end

Note that since you're providing the implementation of #transaction, not merely the return value, you could have also said it this way:

describe '#update_config' do
  it 'makes a YAML::Store and stores A in it within a transaction' do
    mock_store = {}
    mock(mock_store).transaction { |&block| block.call }
    mock(YAML::Store).new { mock_store }
    update_config
    expect(mock_store['A']).to eq 'a'
  end
end
zhon

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!