2014-09-25 52 views
0

我正在使用Watir-Webdriver和RSpec编写Selenium测试,它们在第一次开发时可能有点不准确。我遇到了一种情况,我想在UI上创建一些东西:全部,但是它可能会抛出异常(基于时序或加载不良)。当发生这种情况时,我想截图。RSpec:总是在开始/拯救之前执行(:all)

这是我有:

RSpec.configure do |config| 
    config.before(:all) do |group| #ExampleGroup 
    @browser = Watir::Browser.new $BROWSER 

    begin 
     yield #Fails on yield, there is no block 
    rescue StandardError => e 
     Utilities.create_screenshot(@browser) 
     raise(e) 
    end 
    end 
end 

我运行它,并得到一个错误:

LocalJumpError: no block given (yield)

我以为屈服会工作的原因是之前的RSpec的定义:

def before(*args, &block) 
    hooks.register :append, :before, *args, &block 
end 

如何将我放在before :all中的代码包装在开始/救援区块中,而无需在每个套件上做到这一点?

谢谢先进。

回答

0

您在挂钩之前编写的代码是&您在RSpec::Hooks#before中提到的块。钩子屈服于你的代码,然后在完成屈服之后运行你的测试。

至于如何使这项工作,我认为这应该这样做:

RSpec.configure do |config| 
    # ensures tests are run in order 
    config.order = 'defined' 

    # initiates Watir::Browser before all tests 
    config.before(:all) do 
    @browser = Watir::Browser.new $BROWSER 
    end 

    # executes Utilities.create_screenshot if an exception is raised by RSpec 
    # and the test is tagged with the :first metadata 
    config.around(:each) do |example| 
    example.run 
    Utilities.create_screenshot(@browser) if example.exception && example.metadata[:first] 
    end 
end 

此配置要求第一测试标记有元数据:

describe Thing, :first do 
    it "does something" do 
    # ... 
    end 
end 

这样,你只在运行开始时做一个屏幕截图,测试失败,而不是在每次失败测试后。如果你宁愿不乱用元数据(或者更喜欢你的测试以随机顺序运行),你可以做这样的事情:

RSpec.configure do |config| 
    # initiates Watir::Browser before all tests 
    config.before(:all) do 
    @test_count = 0 
    @browser = Watir::Browser.new $BROWSER 
    end 

    # executes Utilities.create_screenshot if an exception is raised by RSpec 
    # and the test is the first to run 
    config.around(:each) do |example| 
    @test_count += 1 
    example.run 
    Utilities.create_screenshot(@browser) if example.exception && @test_count == 1 
    end 
end 
+0

编辑。当我的意思是'example.metadata [:first]'时,我写了'example [:first]'。 – Johnson 2014-09-25 21:16:49

+0

我需要在之前的截图:所有不是之前:每个。我在之前有导航:所有故意。它需要在那里去除一些重复。我可以使用example.exception来进行特定的测试,但之前:all都给出了example_group不是例子。 – TIMBERings 2014-09-26 01:48:13

+0

好吧,所以你已经设置好了需要在所有测试之前运行一次的代码。如果出现故障或者在所有测试出现故障后,是否需要在第一次测试后进行截图?或者是我完全错过的其他东西? – Johnson 2014-09-26 02:49:09

0

这对我的作品。代替before :all钩子中的begin/rescue

config.after :each do 
    example_exceptions = [] 
    RSpec.world.example_groups.each do |example_group| 
    example_group.examples.each do |example| 
     example_exceptions << !example.exception.nil? 
     end 
    end 
    has_exceptions = example_exceptions.any? {|exception| exception} 
    #Handle if anything has exceptions 
end