除一项外的所有测试的before(:each) [英] before(:each) for all tests except one
问题描述
这是我的 spec_helper.rb
的一部分:
RSpec.configure do |config|
config.before(:each) do
login(email, password)
visit root_url
end
end
除一项外,我在所有(20+)测试中都需要。
that I need in all of my (20+) tests except one.
是否有一种方法可以避免执行单个测试,从而在钩子之前执行
?
Is there a way to avoid that single test to execute the before hook
?
推荐答案
您可以将元数据添加到不需要登录的测试中,然后在钩子
之前评估该元数据。
You can add metadata to tests that do not need to login, then evaluate that metadata in your before
hook.
例如,同一文件中有两个测试。一个需要登录,一个不需要登录。
For example, two tests in the same file. One needs to login and one does not.
# foo_spec.rb
describe Foo do
describe "#bar" do
it "needs to log in" do
expect(1).to eq 1
end
end
describe "#baz" do
it "needs to not log in", :logged_out do
expect(1).to eq 1
end
end
end
因此我们将元数据添加到了 it
块中。接下来,我们配置 before
钩子以评估示例的元数据。
So we added metadata to our it
block. Next, we configure the before
hook to evaluate the example's metadata.
config.before(:each) do |test|
login(email, password) unless test.metadata[:logged_out]
visit root_url
end
现在,每个测试将访问root_url
,但仅访问那些未标记有:logged_out
的用户将调用登录
。
Now, each test will visit root_url
but only the ones not tagged with :logged_out
will call login
.
RSpec调用这些基于元数据的挂钩过滤器。您可以在此处。
RSpec calls these metadata based hooks filters. You can learn a bit more about them here.
这篇关于除一项外的所有测试的before(:each)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!