在套件挂钩之前使用带有标签的RSpec

Gan*_*kar 9 capybara rspec2 ruby-on-rails-3

我正在尝试使用Rspec before(:suite)钩子之类的标签:

  config.before(:suite, :selenium => true) do
    #magical awesomeness
  end
Run Code Online (Sandbox Code Playgroud)

但Rspec似乎不尊重标签并运行我只想运行的代码:selenium => true,无论如何.

奇怪的是,我正在做一个非常类似的事情:每个钩子也似乎工作正常:

  config.around(:each, :selenium => true) do |example|
    Capybara.using_wait_time(10) do
      Capybara.using_driver(:selenium) do
        example.run
      end
    end
  end
Run Code Online (Sandbox Code Playgroud)

谁知道我做错了什么?

Cra*_*son 2

我没有深入研究它,但我的猜测是 :suite 作用域可能在解释任何标签之前运行。据我所知,无论如何你只需要一个 :suite (尽管我可以在你的示例中看到用法)。我认为可以做一个 before :all 会做同样的事情,只要你把它放得足够“高”,就像你的 spec_helper.rb 中所说的那样?

==编辑==

于是我又想了想,我的脑海中浮现出一个解决方案:

# spec_helper.rb
# run with the tag :selenium => true when you set your env var RUN_SELENIUM like so:
# %> RUN_SELENIUM=1 bundle exec rspec spec/
config.filter_run_excluding :selenium => true if ENV['RUN_SELENIUM'].nil?

# now your before suite hook can be something along the lines of
config.before(:suite) do
  if ENV['RUN_SELENIUM'].nil?
    ## regular awesomeness
  else
    ## magical awesomeness
  end
end
Run Code Online (Sandbox Code Playgroud)

我做了类似的事情来使用guard 和guard-spec 来处理标签。当然,您可以使用不带 filter_run_exclusion 的环境变量,这与以下内容相同: %> RUN_SELENIUM=1 bundle exec rspec --tag selenium spec/ 添加配置行只是有助于保持一致。

希望有帮助!