Search code examples
rubyrspecrspec-rails

Around(:each) overriding before(:each)


I am doing some stunts using around each. I found some different odd with around(:each). When I run below example it gives output as:

describe "AroundSpec" do
  before(:each) do
    p "On before each block"
  end

  around(:each) do
    p "On around each block"
  end

  it "1+1 = 2" do
    expect(1+1).to eq(2)
  end
end

output:

  "On around each block"
 .

  Finished in 0.00038 seconds
  1 example, 0 failures

If you notice it doesn't executing before each block. Is this way suppose to be it work or is it a bug in rspec? Thanks in advance


Solution

  • This is because you are using around(:each) wrong I think. In order to do this properly, you have to pass your test into the block as an argument. When you run this test:

    around(:each) do | example |
        p "Before the test"
        example.run
        p "After the test"
    end
    

    The output of your test file using this code would be:

    "Before the test"
    "On before each block"
    "After the test"
    

    What your code is doing is ignoring the before block and just executing your around (the 1+1=2 test is never actually run). The documentation for this can be found here:

    http://rubydoc.info/gems/rspec-core/RSpec/Core/Hooks#around-instance_method