ruby-on-rails – 如何在rails中测试rspec shoulda进行自定义验证?

我的模型中有一个私有方法,如下所示:
validate :record_uniq

  private
  def record_uniq
    if record_already_exists?
      errors.add(:base,"already exists")
    end
  end

  def record_already_exists?
    question_id = measure.question_id
    self.class.joins(:measure).
    where(measures: {question_id: ques_id}).
    where(package_id: pack_id).
    exists?
  end

这种方法更像是一种唯一性范围,可以防止重复记录.我想知道如何使用shoulda或rspec编写验证测试:record_uniq?

我试过的例子:

describe Foo do
  before do
    @bar = Foo.new(enr_rds_measure_id: 1,enr_rds_package_id: 2)
  end

  subject { @bar }

  it { should validate_uniqueness_of(:record_uniq) }
end

解决方法

简单 – 构建一个未通过验证的对象,验证它,并验证是否已设置正确的错误消息.

例如(如果您有一个名为City的模型):

it 'validates that city is unique' do
  city = City.new # add in stuff to make sure it will trip your validation
  city.valid?
  city.should have(1).error_on(:base) # or 
  city.errors(:base).should eq ["already exists"]
end

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...