unit testingRuby块通过模拟与rr(是flexmock)
我如何对以下单元进行unit testing:
def update_config store = YAML::Store.new('config.yaml') store.transaction do store['A'] = 'a' end end
这是我的开始:
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
如何测试块内部的内容?
更新
我已将我的测试转换为规范并切换到rr模拟框架:
describe 'update_config' do it 'calls transaction' do stub(YAML::Store).new do |store| mock(store).transaction end update_config end end
这将测试调用的事务。 如何在块内测试: store['A'] = 'a'
?
首先,您可以更简单地编写这个 – 使用RR的测试不是使用FlexMock进行测试的直接端口。 其次,您根本不测试块内发生的事情,因此您的测试不完整。 试试这个:
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
请注意,既然您提供#transaction的实现,而不仅仅是返回值,您也可以这样说:
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
你想要收益率 :
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
查看此答案,了解相关问题的不同方法。 希望rr api文档能够得到改进。