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