在Rspec中进行特定测试后运行

时间:2018-06-05 01:09:23

标签: ruby testing rspec hook

有没有办法在使用标签的特定测试之后/之前运行after / before块?

我有3个it

describe "describe" do

  it "test1" do
  end

  it "test2" do
  end

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

end

如何在test2之后运行after块?这可能吗?

3 个答案:

答案 0 :(得分:5)

您应该使用context来执行此操作。类似的东西:

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

在块之前/之后具有if / else条件是代码气味。不要这样做。它只会使你的测试变得脆弱,容易出错并且很难改变。

答案 1 :(得分:2)

执行此操作的最佳方法是使用context。以你的例子:

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

答案 2 :(得分:0)

是的,你可以这样做,看看here

您可以使用rspec

中的metadata来实现此目的
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