【问题标题】:rails + rspec : Staying DRY when testing validationsrails + rspec : 在测试验证时保持 DRY
【发布时间】:2010-03-18 12:04:31
【问题描述】:

好吧,假设我有以下模型:

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

这看起来不太干。是否有任何 gem 或插件可以自动执行此类操作? 我想从这些方面得到一些东西:

  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

【问题讨论】:

    标签: ruby-on-rails tdd dry validation


    【解决方案1】:

    这很了不起:http://github.com/carlosbrando/remarkable

    以后可以做

    it { should validate_presence_of :name }
    

    【讨论】:

    • 这正是我想要的。谢谢!
    • 如果我有自定义验证方法怎么办?例如类用户验证:check_my_stuff end
    【解决方案2】:

    如果您使用的是 factory_girl,您可以这样做:

      it "should be invalid without a name" do
        FactoryGirl.build(:country, name: nil).should_not be_valid
      end
    

    一个建议...不要在每个规范中都使用关键字“应该”。 而是写:“无名无效”

    【讨论】:

    • +1 表示“应该”建议。自从我写这篇文章以来,我已经迁移到“should-less”规范。
    • @Cyle 因为描述应该用现在时。
    • @Zenph 但是如果将来出现问题,您的描述会变得无效怎么办?我认为指定期望的结果更有意义。
    • @Cyle 好吧,这是测试社区的惯例 :) 为什么要反对一种受欢迎的做法?检查您最喜欢的公司的 gem 的源代码。这种描述方式现在很普遍是有原因的。
    • 进一步(不是指你 Cyle),这个特定的规范给出了误报。仅仅因为没有名称的模型无效,并不意味着缺少名称会导致无效。在接受的答案中检查errors_on(:name) 或简单地validates_presence_of 要好得多。
    【解决方案3】:

    也试试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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-06
      • 1970-01-01
      • 2011-11-24
      • 1970-01-01
      • 2020-08-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多