Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/61.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 在特定上下文之前只运行一次特定代码_Ruby On Rails_Ruby_Rspec - Fatal编程技术网

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