2013-04-07 60 views
0

我如何单元测试如下:单元测试Ruby块与RR惩戒(是flexmock)

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'

回答

0

要拨打产量

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 

退房this answer一种不同的方法,以一个相关的问题。希望rr api documentation会有所改善。

1

首先,你可以写得更简单 - 使用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 
+0

谢谢。这个问题最初是如何测试Flexmock中的块内部的。我改变了rr,因为没有人回答了几个月。 – zhon 2013-10-07 20:26:24