RSpec 模拟,“name”在示例组中不可用

dfa*_*ken 7 ruby rspec

我有以下 Ruby 代码:

def report_deviation(departure)
  deviation = departure.fetch('Dev')
  trip = departure.fetch('Trip')
  run_id = trip.fetch('RunId')
  headsign = trip.fetch('InternetServiceDesc')
  timestamp = Time.now.strftime '%l:%M %P'
  FileUtils.mkdir 'log' unless File.directory? 'log'
  File.open DAILY_LOG_FILE, 'a' do |file|
    file.puts "#{timestamp}, #{name}: Run #{run_id} (#{headsign}), deviation #{deviation}"
  end
end
Run Code Online (Sandbox Code Playgroud)

通过以下 RSpec 代码测试:

describe 'report_deviation' do
  let(:departure) { double }
  let(:trip) { double }
  let(:file) { double }
  it 'appends to a log file with the correct entry format' do
    expect(departure).to receive(:fetch).with('Trip').and_return trip
    expect(departure).to receive(:fetch).with('Dev').and_return 'DEVIATION'
    expect(trip).to receive(:fetch).with('RunId')
      .and_return 'RUN'
    expect(trip).to receive(:fetch).with('InternetServiceDesc')
      .and_return 'HEADSIGN'
    stub_const 'DeviationValidator::DAILY_LOG_FILE', :log_file
    expect(File).to receive(:open).with(:log_file, 'a').and_yield file
    timestamp = '12:00 pm: Run RUN (HEADSIGN), deviation DEVIATION'
    expect(file).to receive(:puts).with timestamp
    Timecop.freeze(Time.new 2017, 7, 31, 12) { report_deviation(departure) }
  end
end
Run Code Online (Sandbox Code Playgroud)

但是当我运行时,我收到失败消息:

`name` is not available from within an example (e.g. an `it` block) or from constructs that run in the scope of an example (e.g. `before`, `let`, etc). It is only available on an example group (e.g. a `describe` or `context` block).
Run Code Online (Sandbox Code Playgroud)

这个词name没有写在这里的任何地方,如果我删除测试的最后一行(它调用实际的代码),我会得到我期望的不令人满意的异常的测试失败。我通常会将代码归结为导致错误的部分,但我不知道是什么导致了错误。

就其价值而言,回溯中提到的特定行号是块file.puts内的File.open- 但我不明白为什么这会导致失败。我已经设置了测试双打,使得这些对象没有什么特别的 - Filereceiveopen和 Yields file,它们唯一的工作就是监听puts我期望的字符串的接收。那么哪一段代码正在调用关键字 RSpec 方法呢name

jac*_*614 15

问题来自 rspec gem,如果您使用的是 Rails 6,则需要使用gem 'rspec-rails', '~> 4.1.0'

  • 准确地说,在 Rails 6.0.3.1 上没有出现此错误,但在 6.1.4.6 上出现了。但是,是的,'rspec-rails' gem 就是原因。 (2认同)

Igo*_*dov 3

name不是关键字方法,它是尝试调用的RSpec方法report_deviation

file.puts "#{timestamp}, #{name}: Run #{run_id} (#{headsign}), deviation #{deviation}"
Run Code Online (Sandbox Code Playgroud)

但方法没有定义。

您需要在定义的name类中定义该方法report_deviation。或者,如果report_deviation在规范文件中定义并使用,则添加一个名为的简单变量name

describe 'report_deviation' do
  let(:departure) { double }
  let(:trip) { double }
  let(:file) { double }
  let(:name) { "simple name" }
  ...
Run Code Online (Sandbox Code Playgroud)