如何在rspec中的“it”语句中添加变量?

时间:2013-08-09 21:26:50

标签: ruby-on-rails ruby rspec

如果我有

let(:analysis_file_1) { "./spec/test_files/analysis1.json" }
...
it "should have message x" do

我想在“it”语句中打印出analysis_file_1的值。

但这不起作用:

it "#{analysis_file_1} should have message x" do

错误
in `block in <top (required)>': undefined local variable or method `analysis_file_1' for #<Class:0x007f865a219c00> (NameError)

有没有办法在它的消息中使用let定义的变量?

2 个答案:

答案 0 :(得分:1)

您可以像这样定义一个常量:

ANALYSIS_FILE_1 = "./spec/test_files/analysis1.json"

it "#{ANALYSIS_FILE_1} should have message x" do

如果您有多个分析文件,可以将它们放在一个数组中:

["./spec/test_files/analysis1.json", "./spec/test_files/analysis2.json", "./spec/test_files/analysis3.json"].each do |analysis_file|
  it "#{analysis_file} should have message x" do
    # Your spec here
  end
end

答案 1 :(得分:-3)

您必须使用符号:

it "#{:analysis_file_1} should have message x"

==

正如Peter Klipfel所说,声明一个局部变量对我有用:

analysis_file_1 = "./spec/test_files/analysis1.json"

it "#{analysis_file_1} should have message x" do

我无法得到sevenseacat的建议。这样:

describe "Joe" do
  subject(:last) { "Smith" }

  it "should have message x"  do 
    pending
  end
end

产生了输出:

Pending:
  Joe should have message x
    # No reason given
    # ./spec/requests/static_pages_spec.rb:6

我希望输出为:

Pending:
  Joe Smith should have message x