Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/facebook/8.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 Rspec让变量在块之前输入,不在示例之间更改_Ruby On Rails_Ruby_Rspec - Fatal编程技术网

Ruby on rails Rspec让变量在块之前输入,不在示例之间更改

Ruby on rails Rspec让变量在块之前输入,不在示例之间更改,ruby-on-rails,ruby,rspec,Ruby On Rails,Ruby,Rspec,在rspec 3.2中,我有一些基于以下伪代码的东西: context 'my test context' do before do method_that_uses(error_message) end subject { post :my_action, params: a_bunch_of_params } let(:error_message) { 'error' } it { is_expected.to raise_error(MyException

在rspec 3.2中,我有一些基于以下伪代码的东西:

context 'my test context' do
  before do
    method_that_uses(error_message)
  end

  subject { post :my_action, params: a_bunch_of_params }

  let(:error_message) { 'error' }

  it { is_expected.to raise_error(MyException) }

  let(:error_message) { 'different error' }

  it { is_expected.to redirect_to(a_path) }

  let(:error_message) { 'third error' }

  it { is_expected.to redirect_to(another_path) }
end

每个示例运行时都会将
error\u message
设置为
third error
。我也通过从前吊钩上撬动pry来确认这一点。如何获得所需的行为?

这是因为在内部,
使用,如中所示。您可以创建一个快速示例

class A
  def create_method(name, &block)
    self.class.send(:define_method, name, &block)
  end
end

a = A.new
a.create_method(:foo) { puts "bar" }
a.create_method(:foo) { puts "baz" }
a.foo
然后运行它,您将看到
define_方法
用新方法覆盖以前的方法。因此,在您的示例中,您正在创建一个方法,然后在有机会调用它之前重写它的定义两次

您希望在其自身的上下文中运行每个
错误消息,如下所示:

def method_that_uses(e)
  puts "running with: #{e}"
end

context 'my test context' do
  before do
    method_that_uses(error_message)
  end

  context 'error' do
    let(:error_message) { 'error' }

    it { puts "run one" }
  end

  context 'second error' do
    let(:error_message) { 'different error' }

    it { puts "run two" }
  end

  context' third error' do
    let(:error_message) { 'third error' }

    it { puts "run three" }
  end
end
当运行时,输出

running with: error
run one
.running with: different error
run two
.running with: third error
run three
.
这是因为
描述
上下文
块创建了一个新的
示例组
(),并声明

示例组主体(例如
描述
上下文
块)在ExampleGroup的新子类的上下文中进行评估


所以,
let(:error\u message)
现在正在不同的子类上定义这些方法。

回答得很好。非常感谢。我想将来我应该深入到源头。不管怎样,我现在完全明白原因了。