我有上有唯一性驗證ActiveRecord模型:如何在沒有數據庫的ActiveRecord模型規範中模擬唯一性驗證錯誤?
class Profile < ActiveRecord::Base
# fields: :name, :slug
before_validation :set_default_slug_from_name
validates :slug, uniqueness: {case_sensitive: false},
unless: -> { |p| p.slug.blank? }
# ...
end
現在,書寫規範這個模型時,我想模擬唯一性驗證錯誤而無需訪問數據庫所以我可以測試
describe Profile
before { subject.name = "Bob Greenfield" }
it "modifies the beginning of the slug if there is a duplicate" do
# simulate uniqueness conflict (duplicate record) here
subject.valid?
expect(subject.slug).to match(/^\w+-bob-greenfield$/)
end
end
我挖成實現像UniquenessValidator
和嘗試的東西Rails code:
allow_any_instance_of(ActiveRecord::Relation).to receive(:exists?).and_return(true)
# ...
但是,這似乎並沒有工作。