Ruby on rails 在特定上下文之前只运行一次特定代码
我想在一个特定的上下文之前运行一个特定的代码块,它应该只运行一次。我尝试将元数据用于上下文块,但它会在每个示例之前调用我的代码块Ruby on rails 在特定上下文之前只运行一次特定代码,ruby-on-rails,ruby,rspec,Ruby On Rails,Ruby,Rspec,我想在一个特定的上下文之前运行一个特定的代码块,它应该只运行一次。我尝试将元数据用于上下文块,但它会在每个示例之前调用我的代码块 before do |context| p 'test test' if context.medata[:something] end ... describe '#execute' do context 'header with timelog fields', :something do it '123' do expect(true)
before do |context|
p 'test test' if context.medata[:something]
end
...
describe '#execute' do
context 'header with timelog fields', :something do
it '123' do
expect(true).to eq true
end
it '234' do
expect(true).to eq true
end
end
end
运行rspec时,
test-test
出现两次。在rspec
中,在之前写入是(:each)
之前的的简写
相反,您需要在(:all)
之前使用:
你能有几个这样的上下文吗?如果是,那么您希望该块运行多少次?您的问题是什么?什么是medata?但是,在编写这样的代码时需要小心!在测试中更改系统的“全局状态”通常被认为是不好的。您应该“让系统保持原样”,否则您可能会因测试以随机顺序运行而导致间歇性测试失败。不过,这种模式有一些合法的用例。根据“<代码>之前(所有)实际上正在做的事情,考虑也定义了<代码>((所有)”< /C> >将“重置”系统恢复到正常状态。
describe '#execute' do
context 'header with timelog fields' do
before(:all) do
p 'test test'
end
it '123' do
expect(true).to eq true
end
it '234' do
expect(true).to eq true
end
end
end