rails + rspec:测试验证时保持干燥状态

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)

shi*_*ara 9

值得注意的是:http://github.com/carlosbrando/remarkable

你能做到之后

it { should validate_presence_of :name }
Run Code Online (Sandbox Code Playgroud)

  • 如果我有自定义验证方法怎么办?例如,类用户验证:check_my_stuff结束 (3认同)

Mic*_*art 5

如果你正在使用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".相反,写道:"没有名字就无效"

  • 为"应该"推荐+1.自从我写这篇文章以来,我已经迁移到了"应该减少"的规范. (2认同)