[英]RSpec: Always execute before(:all) in begin/rescue
我正在使用Watir-Webdriver和RSpec編寫Selenium測試,當它們最初被開發時,它們可能有點參差不齊。 我遇到了一種情況,我想在:all之前在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:未提供任何塊(產量)
我認為屈服的原因是RSpec之前的定義:
def before(*args, &block)
hooks.register :append, :before, *args, &block
end
我該如何包裝之前放入的代碼before :all
包裝在begin / rescue塊中,而不必在每個套件中都這樣做?
提前致謝。
您在before鈎子中編寫的代碼是在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
這對我有用。 而不是before :all
鈎子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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.