繁体   English   中英

在RSpec中将示例从“ it”块传递到“ let”块

[英]Passing an example from “it” block to “let” block in RSpec

我正在观看有关使用RSpec的代码学校的截屏视频,它有以下几行:

describe Game do
  describe '#call' do
    let(:description) do |example|
      example.description
    end

    context 'when the choices are different' do

      subject(:game) { described_class.new }
      it 'rock beats scissors' do |example|
        expect(subject.call('rock', 'scissors')).to eq(description)
      end
    end
  end
end

我不太明白example参数如何进入“ let”块? 那是Ruby还是RSpec魔术? 谢谢。

请参阅rspec-core源中的以下行:

# Simplified version of the code:
def let(name, &block)
  # ...
  if block.arity == 1
    define_method(name) { super(RSpec.current_example, &nil) }
  # ...
end

因为对每个测试都会重新评估let ,所以可以重新定义它以包括当前测试上下文的知识。

另外值得注意的是RSpec.current_example线程安全的

def self.current_example
  RSpec::Support.thread_local_data[:current_example]
end

这意味着,即使您正在运行并行测试,每个let块也将始终能够正确地重新评估当前示例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM