kik*_*ito 4 validation tdd ruby-on-rails dry
好吧我说我有以下型号:
class Country < ActiveRecord::Base
validates_presence_of :name
validates_presence_of :code
end
Run Code Online (Sandbox Code Playgroud)
我正在为那些验证做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
Run Code Online (Sandbox Code Playgroud)
这看起来不太干.有没有自动化这种东西的宝石或插件?我希望得到以下几点:
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
Run Code Online (Sandbox Code Playgroud)
值得注意的是:http://github.com/carlosbrando/remarkable
你能做到之后
it { should validate_presence_of :name }
Run Code Online (Sandbox Code Playgroud)
如果你正在使用factory_girl,你可以这样做:
it "should be invalid without a name" do
FactoryGirl.build(:country, name: nil).should_not be_valid
end
Run Code Online (Sandbox Code Playgroud)
一个建议......不要在每个规范上使用关键字"should".相反,写道:"没有名字就无效"
归档时间: |
|
查看次数: |
6280 次 |
最近记录: |