这是我的验证测试,我想找到编写模型规范的最佳方法,尤其是验证。但我在下面的代码中遇到问题。
require 'spec_helper'
describe Ad, :focus do
let(:ad) { Ad.sham!(:build) }
specify { ad.should be_valid }
it "not creates a new instane given a invalid attribute" do
ad = Ad.new
ad.should_not be_valid
end
[:title, :category_id, :email, :ad_content, :name, :price].each do |attr|
it "should require a #{attr}" do
subject.errors[attr].should include("blank")
end
end
end
当我运行此规范时,我收到此错误:
5) Ad should require a name
Failure/Error: subject.errors[attr].should include("blank")
expected [] to include "blank"
Diff:
@@ -1,2 +1,2 @@
-blank
+[]
# ./spec/model/ad_spec.rb:15:in `block (3 levels) in <top (required)>'
答案 0 :(得分:4)
此处的问题是,在检查错误之前,您未在该示例中调用valid?
。您在前一个示例中(间接)调用它,但不是您声明有错误的那个。
正确的方法是:
[:title, :category_id, :email, :ad_content, :name, :price].each do |attr|
it "should require a #{attr}" do
subject.valid?
subject.errors[attr].should include("blank")
end
end