37

我正在使用 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没有通过(不在范围内?)我如何让这样的事情起作用?

4

1 回答 1

57

问题是示例组内与钩子内self不同,因此即使它具有相同的名称,它也不是同一个实例变量。selfbefore

我建议您用于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
于 2012-07-06T06:11:15.517 回答