9

モデルには、次のようなプライベートメソッドがあります。

  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

このメソッドは、uniquenessレコードの重複を防ぐためのスコープのようなものです。validate :record_uniqまたはを使用してテストを作成する方法を知りたいです shouldarspec

私が試したことの例:

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
4

2 に答える 2

10

シンプル-検証に失敗するオブジェクトを作成し、検証して、正しいエラーメッセージが設定されていることを確認します。

たとえば(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
于 2013-03-27T11:25:34.323 に答える
9

これが、RSpec3構文を使用して行うことです。

it 'validates that city is unique' do
  city = City.new('already taken name')
  expect(city).to be_invalid
  expect(city.errors[:base]).to include('already exists')
end
于 2016-06-21T18:53:49.700 に答える