Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Rspec save_and_open_page automatically when any spec fails

Tags:

rspec

capybara

I have...

/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

So as soon as any spec fails, Rspec quits and shows you the error.

At the point, I'd like Rspec to also automatically call Capybara's save_and_open_page method. How can I do this?

Capybara-Screenshot looks promising, but while it saves both the HTML and a screenshot as an image file (which I don't need), it does not automatically open them.

like image 367
steven_noble Avatar asked Dec 21 '12 00:12

steven_noble


2 Answers

In the rspec's configuration you could define an after hook (https://www.relishapp.com/rspec/rspec-core/v/2-2/docs/hooks/before-and-after-hooks) for each example. It's not very well documented but the block for this hook could take an example param. On the example object you could test:

  • is it a feature spec: example.metadata[:type] == :feature
  • has it failed: example.exception.present?

The complete code snipped should look like:

  # 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
like image 95
luacassus Avatar answered Sep 27 '22 23:09

luacassus


In RSpec 2 in conjunction with Rails 4, I use this config block:

# 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
like image 41
Thomas Klemm Avatar answered Sep 27 '22 22:09

Thomas Klemm