如何将实例变量传递给RSpec共享示例

时间:2012-07-06 01:33:36

标签: ruby-on-rails rspec2

我正在使用RSpec(2.10.1)来测试模型上的验证,并提取了一些代码以与其他模型验证共享。验证首先写在Companies表上,因此代码如下所示:

# support/shared_examples.rb
shared_examples "a text field" do |field, fill, length|
  it "it should be long enough" do
    @company.send("#{field}=", fill * length)
    @company.should be_valid
  end

  etc...
end

,用法是:

# company_spec.rb
describe Company do
  before { @company = Company.new( init stuff here ) }

  describe "when address2" do
    it_behaves_like "a text field", "address2", "a", Company.address2.limit
  end

  etc...
end

我想将@company作为参数传递给共享示例,以便我可以将代码重用于不同的模型,如下所示:

# support/shared_examples.rb
shared_examples "a text field" do |model, field, fill, length|
  it "it should be long enough" do
    model.send("#{field}=", fill * length)
    model.should be_valid
  end

  etc...
end

,用法是:

# company_spec.rb
describe Company do
  before { @company = Company.new( init stuff here ) }

  describe "when address2" do
    it_behaves_like "a text field", @company, "address2", "a", Company.address2.limit
  end

  etc...
end

然而,当我这样做时,我得到undefined method 'address2' for nil:NilClass。看来@company没有被传递(不在范围内?)如何让这样的东西起作用?

1 个答案:

答案 0 :(得分:53)

问题是示例组中的selfself挂钩中的before不同,因此即使它具有相同的名称,它也不是相同的实例变量。

我建议您使用let来处理以下情况:

# support/shared_examples.rb
shared_examples "a text field" do |field, fill, length|
  it "it should be long enough" do
    model.send("#{field}=", fill * length)
    model.should be_valid
  end
end

# company_spec.rb
describe Company do
  describe "when address2" do
    it_behaves_like "a text field", "address2", "a", Company.address2.limit do
      let(:model) { Company.new( init stuff here ) }
    end
  end
end