有没有办法在RSpec中首先运行嵌套之前的过滤器?

时间:2017-01-24 18:21:35

标签: ruby-on-rails ruby rspec

describe 'Feature' do
  before do
    setup
  end

  describe 'Success' do
    before do
      setup_for_success
    end

    specify 'It works' do
      ...
    end
  end
end

RSpec将始终在setup之前运行setup_for_success。有没有办法先运行setup_for_success

3 个答案:

答案 0 :(得分:3)

您可以通过确定before(:all)before(:each)尝试此操作之前运行来实现此目的:

describe 'Feature' do
  before(:each) do
    puts "second"
  end

  describe 'Success' do
    before(:all) do
      puts "first"
    end

    specify 'It works' do
      ...
    end
  end
end

# =>
10:29:54 - INFO - Running: spec
Run options: include {:focus=>true}
first
second
.

Finished in 0.25793 seconds (files took 2.52 seconds to load)
1 example, 0 failures

编辑:

在Rspec 2中,操作按此顺序运行:

before suite
before all
before each
after each
after all
after suite

以下是显示调用方法顺序的文档的链接:https://www.relishapp.com/rspec/rspec-core/v/2-2/docs/hooks/before-and-after-hooks#before/after-blocks-are-run-in-order

显然在Rspec 3.5中,前块调用具有不同的命名也可以。它们按此顺序运行:

before :suite
before :context
before :example
after  :example
after  :context
after  :suite

describe 'Feature' do
  before(:example) do
    puts "second"
  end

  describe 'Success' do
    before(:context) do
      puts "first"
    end

    specify 'It works' do
      ...
    end
  end
end

10:59:45 - INFO - Running: spec
Run options: include {:focus=>true}
first
second
.

Finished in 0.06367 seconds (files took 2.57 seconds to load)
1 example, 0 failures

以下是较新的文档: http://www.relishapp.com/rspec/rspec-core/v/3-5/docs/hooks/before-and-after-hooks

答案 1 :(得分:2)

before过滤器按照指定的顺序附加。从RSpec 2.10.0开始,您可以通过使它们成为prepend_before过滤器来添加它们。

同样,after过滤器默认为预先添加,但您可以append_after代替它们。

您的代码最终会如下所示(为简洁起见):

describe 'Feature' do
  before { setup }

  describe 'Success' do
    prepend_before { setup_for_success }

    it 'works' { ... }
  end
end

答案 2 :(得分:0)

您似乎在嵌套上下文中添加了外部所需的内容,这有点奇怪。我怀疑您在所有嵌套上下文中都不需要该设置。如果是这种情况,则需要过滤钩子。

RSpec.describe 'Feature' do
  before :each, success: true do
    setup_for_success
  end

  before :each do
    setup
  end

  describe 'Success', success: true do
    specify 'It works' do
      ...
    end
  end

  describe 'Fail' do
    specify 'Won´t work' do
      ...
    end
  end
end

您可以不进行嵌套:

RSpec.describe 'Feature' do
  before :each, success: true do
    setup_for_success
  end

  before :each do
    setup
  end

  specify 'It works', success: true do
    ...
  end

  specify 'Won´t work' do
    ...
  end
end

这是文档的链接:

https://relishapp.com/rspec/rspec-core/docs/hooks/filters