好吧我说我有以下型号:
class Country < ActiveRecord::Base
validates_presence_of :name
validates_presence_of :code
end
我正在为这些验证进行rspec单元测试。它们看起来像这样:
it "should be invalid without a name" do
country = Country.new(@valid_attributes.except(:name))
country.should_not be_valid
country.errors.on(:name).should == "can't be blank"
country.name = @valid_attributes[:name]
country.should be_valid
end
it "should be invalid without a code" do
country = Country.new(@valid_attributes.except(:code))
country.should_not be_valid
country.errors.on(:code).should == "can't be blank"
country.code = @valid_attributes[:code]
country.should be_valid
end
这看起来不太干。有没有自动化这种东西的宝石或插件? 我希望得到以下几点:
it "should be invalid without a name" do
test_presence_validation :name
end
it "should be invalid without a code" do
test_presence_validation :code
end
答案 0 :(得分:9)
答案 1 :(得分:5)
如果您使用 factory_girl ,则可以执行以下操作:
it "should be invalid without a name" do
FactoryGirl.build(:country, name: nil).should_not be_valid
end
一个建议......不要在每个规范上使用关键字“should”。 相反,写道:“没有名字就无效”
答案 2 :(得分:0)
还要尝试accept_values_for gem。 它允许做这样的事情:
describe User do
subject { User.new(@valid_attributes)}
it { should accept_values_for(:email, "john@example.com", "lambda@gusiev.com") }
it { should_not accept_values_for(:email, "invalid", nil, "a@b", "john@.com") }
end