我正在编写Selenium测试,使用Watir-Webdriver和RSpec,当他们第一次开发时可能有点不稳定。我遇到过一种情况,我想在之前的UI上创建一些东西:所有,但它可以抛出异常(基于时间或加载不良)。当发生这种情况时,我想截取屏幕截图。
这就是我所拥有的:
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:没有给定块(yield)
我认为屈服的原因是RSpec对之前的定义:
def before(*args, &block)
hooks.register :append, :before, *args, &block
end
如何将我放在before :all
中的代码包装在开始/救援块中,而不必在每个套件上执行此操作?
先谢谢。
答案 0 :(得分:0)
您在前钩中写的代码是您在RSpec::Hooks#before
中引用的& block。钩子产生代码,然后在产量完成后运行测试。
至于如何使这项工作,我认为应该这样做:
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
答案 1 :(得分:0)
这对我有用。而不是begin/rescue
钩子中的before :all
,
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