Question: Adding `after` block in rspec helper module

Question

Adding `after` block in rspec helper module

Answers 2
Added at 2017-07-20 02:07
Tags
Question

I've got a module of helpers which is include'd in an RSpec.describe block. Most methods in there are related to managing logged in / logged out status, so I'd like to make sure anything using that helper automatically cleans up the global state to avoid leaking doubles/mocks.

But every example I see in the docs seems to be about adding just the helper methods, not extra before / after blocks.

Can I add an extra after block which won't override the existing ones from the helper module?

Answers to

Adding `after` block in rspec helper module

nr: #1 dodano: 2017-07-23 13:07

If I'm understanding your question properly, something like this should do the trick. (Example is that first one on your link with after blocks added.)

helpers.rb

module Helpers
  def help
    :available
  end

  def self.included(base)
    base.after(:each) do
      puts "after in helpers.rb"
    end
  end
end

example.rb

require './helpers'
RSpec.configure do |c|
  c.include Helpers
end

RSpec.describe "an example group" do
  after(:each) do
    puts "After in example.rb"
  end

  it "has access to the helper methods defined in the module" do
    expect(help).to be(:available)
  end
end

and then running it

$ rspec example.rb
# After in example.rb
# after in helpers.rb
# .
# Finished in 0.00196 seconds (files took 0.07939 seconds to load)
# 1 example, 0 failures

If I misunderstood the question, let me know and I can clarify further or alter the example

nr: #2 dodano: 2017-07-23 15:07

The answer is yes. Every before | after block created inside your test will run before the before | after block on Helper file.

So your blocks will not override the helper blocks.

Source Show
◀ Wstecz