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

我使用RSpec(2.10.1)在模型上testingvalidation,并提取了一些代码与其他模型validation共享。 validation首先写在公司表上,所以代码如下所示:

# 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作为parameter passing给共享示例,以便可以针对不同模型重用代码,如下所示:

 # 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公司没有被通过(不在范围内)?我如何得到这样的工作?

问题是,示例组中的selfbefore钩子中的self不同,所以即使它具有相同的名称也不是同一个实例variables。

我build议你使用这样的例子:

 # 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