AutomateFr33k
AutomateFr33k

Reputation: 602

Run after block after specific test in Rspec

Is there a way I can run the after/before block after/before a specific test using labels?

I have 3 it blocks

describe "describe" do

  it "test1" do
  end

  it "test2" do
  end

  after(<<what goes here??>>) do
  end

end

How do I run the after block only after test2? Is that possible?

Upvotes: 3

Views: 3780

Answers (3)

Caleb Keene
Caleb Keene

Reputation: 388

The best way to do this is just use a context. For your example:

describe "AutomateFr33k's fr33ky tests" do

  it "runs test1" do
    expect(true).to be_true
  end

  context "do something afterwards" do
    after { puts "running something after test2!" }

    it "runs test2" do
      expect(5).not_to eq(4)
    end
  end
end

Upvotes: 2

Gavin Miller
Gavin Miller

Reputation: 43815

You should use contexts to do this. Something like:

describe "describe" do
  context 'logged in' do
    before(:each) do
      # thing that happens in logged in context
    end

    after(:each) do
      # thing that happens in logged in context
    end

    it "test1" do
    end
  end

  context 'not logged in' do
    # No before/after hooks here. Just beautiful test isolation

    it "test2" do
    end
  end
end

Having if/else conditions in before/after blocks is a code smell. Don't do it that way. It'll only make your tests brittle, error prone, and hard to change.

Upvotes: 7

Subash
Subash

Reputation: 3168

Yes you can do that, have a look here

You can achieve that using metadata in rspec

RSpec.configure do |config|
  config.treat_symbols_as_metadata_keys_with_true_values = true
end

describe "Skip hook demo" do
  # If prior to RSpec 2.99.0.beta1
  after do
    puts "before hook" unless example.metadata[:skip]
  end

  # If RSpec 2.99.0.beta1 or later
  after do |example|
    puts "before hook" unless example.metadata[:skip]
  end

  it "will use before hook" do
  end

  it "will not use before hook", :skip do
  end
end

Upvotes: 1

Related Questions