Rspec :在失败时保存实例变量值



我正在测试一种基于 json 的方法。该方法采用 json 数组列表。当 json 数组按顺序出现时,该方法工作正常,当数组随机化时,该方法会中断。对于所有随机病例,它都不会失败。因此,在失败时,我想保存 json 数组的值。有什么办法可以做到这一点吗?

describe 'when the flat hash comes in random order' do
  it 'knows how to create the parent nodes first' do
    do_stuff_and_validate(@flat_hash[:nodeList].shuffle!)
  end
end

您可以定义自定义匹配器并覆盖失败消息以显示所需的内容。

以下示例从 RSpec 文档复制:

require 'rspec/expectations'
RSpec::Matchers.define :be_a_multiple_of do |expected|
  match do |actual|
    actual % expected == 0
  end
  failure_message_for_should do |actual|
    "expected that #{actual} would be a multiple of #{expected}"
  end
end
# fail intentionally to generate expected output
describe 9 do
  it {should be_a_multiple_of(4)}
end

您可以将此数组写入文件以供以后检查。

File.open("hash.txt", 'w') do |f|
  f.write(your_json_array)
end

我使用了开始-救援-重新抚养技巧。

begin
  # The assertions
rescue Exception => e
  pp @flat_hash
  raise e
end

最新更新