【问题标题】:How to make Rspec save_and_open_page automatically when any spec fails当任何规范失败时如何自动制作Rspec save_and_open_page
【发布时间】:2014-11-17 18:29:17
【问题描述】:

我有……

/spec/spec_helper.rb

require 'capybara/rspec'
require 'capybara/rails'
require 'capybara/dsl'

RSpec.configure do |config|
  config.fail_fast = true
  config.use_instantiated_fixtures = false 
  config.include(Capybara, :type => :integration)
end

因此,一旦任何规范失败,Rspec 就会退出并向您显示错误。

此时,我希望 Rspec 也自动调用 Capybara 的 save_and_open_page 方法。我该怎么做?

Capybara-Screenshot 看起来很有希望,但是虽然它将 HTML 和屏幕截图保存为图像文件(我不需要),但它不会自动打开它们。

【问题讨论】:

    标签: rspec capybara


    【解决方案1】:

    在 rspec 的配置中,您可以为每个示例定义一个后挂钩 (https://www.relishapp.com/rspec/rspec-core/v/2-2/docs/hooks/before-and-after-hooks)。它没有很好的记录,但这个钩子的块可能需要一个example 参数。您可以在 example 对象上进行测试:

    • 是功能规格吗:example.metadata[:type] == :feature
    • 是否失败:example.exception.present?

    截取的完整代码应如下所示:

      # RSpec 2
      RSpec.configure do |config|
        config.after do
          if example.metadata[:type] == :feature and example.exception.present?
            save_and_open_page
          end
        end
      end
    
      # RSpec 3
      RSpec.configure do |config|
        config.after do |example|
          if example.metadata[:type] == :feature and example.exception.present?
            save_and_open_page
          end
        end
      end
    

    【讨论】:

    • Rspec 3 需要明确输入 do |example| 才能工作
    【解决方案2】:

    在 RSpec 2 和 Rails 4 中,我使用了这个配置块:

    # In spec/spec_helper.rb or spec/support/name_it_as_you_wish.rb
    #
    # Automatically save and open the page
    # whenever an expectation is not met in a features spec
    RSpec.configure do |config|
      config.after(:each) do
        if example.metadata[:type] == :feature and example.exception.present?
          save_and_open_page
        end
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-19
      • 2012-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多