rspec:如何在第一次失败后继续测试

时间:2013-09-16 13:04:53

标签: ruby loops testing rspec

我正在使用rspec对设备进行系统测试。该设备是模块化的,因此任何数量的子设备都可以连接到测试台。我想在很多地方编写测试,这些测试将遍历连接的子设备并在每个设备上运行相同的测试。

基本上,这就是我想要做的事情:

before(:all)   
  @tool = discover_sub_devices()
  @tool.sub_devices.should == exp_sub_device_list
end

describe "some sub device tests" do
  @tool.sub_devices.each do |dev|   
    it "should succeed at doing things" do
      dev.do_thing.should == success   
    end 
  end
end

不幸的是,这不起作用。我得到错误,说@tool是nill,并且在测试运行之前不包含类sub_devices。因此,在before(:all)块运行之前,正在解析测试。

我可以使其工作的一种方法是将循环置于it块内。像这样:

it "should succeed at doing things" do
  @tool.sub_devices.each do |dev| 
    dev.do_thing.should == success   
  end
end

这样做的问题是我真的想要测试所有子设备,即使第一个子设备出现故障。我想看一个确切的子设备有多少故障的报告。一旦失败,该代码就会爆发,而不会测试其余代码。

我意识到这可能不是rspec的正常使用案例,但如果我可以做到这一点,它对我们的测试情况会非常方便。

有什么建议吗?

2 个答案:

答案 0 :(得分:1)

以下是编写此内容的一些技巧。

最好避免使用before :all。最好避免在示例之外创建对象。

describe "some sub device tests" do

  let(:tool) { discover_sub_devices }

  it "matches the sub device list" do
    tool.sub_devices.should be == expected_sub_devices_list
  end

  it "succeeds with all sub-devices" do
    failures = tool.sub_devices.reject{|d| d.do_thing == success}

    # option 1
    failures.should be_empty # will show just a yes/no result

    # option 2
    failures.size.should be == 0 # will show the number of failures

    # option 3
    failures.should be == [] # will display all sub-devices which fail
  end

end

答案 1 :(得分:0)

您遇到的问题是describe块的正文会立即执行,letbeforeit块的正文会被执行在以后执行。

假设您不需要每次都重新发现设备,您可以按照以下方式重构代码,取消before来电:

describe "some sub device tests" do
  tool = discover_sub_devices()
  it "should discover sub devices correctly" do
     tool.sub_devices.should == exp_sub_device_list
  end
  tool.sub_devices.each do |dev|   
    it "should succeed at doing things" do
      dev.do_thing.should == success   
    end 
  end
end
相关问题