Order of Execution of Before Blocks in RSpec

I discovered that before blocks in RSpec’s examples are executed in the order they are declared. There is no great deal about it, but it can be useful when using shared examples.
In rspec 1.3.8, it is possible to simulate shared examples with parameters by using instance variables instead. This is were it gets useful to know the order of evaluation of before blocks. As an example :

1
2
3
4
5
6
7
8
9
10
11
12
shared_example_for "anything" do
  before :each do
    @thing.should_not be_nil
  end
end

describe "A monkey wrench" do
  it_should_behave_like "anything"
   before :each do
    @thing = MonkeyWrench.new
  end
end

The previous example will fail, whereas the next one will succeed.

1
2
3
4
5
6
describe "A monkey wrench" do
  before :each do
    @thing = MonkeyWrench.new
  end
  it_should_behave_like "anything"
end

That is the before blocks nested in shared examples still evaluate in the order of declaration.

Comments