开发者

Rails/Rspec: Testing uniqueness validations in models without touching the database

开发者 https://www.devze.com 2023-03-19 16:45 出处:网络
I current test uniqueness validations in rspec using something like the following: @unique = Unique.create!(:uni开发者_如何学Goque_field => \'unique_value\')

I current test uniqueness validations in rspec using something like the following:

@unique = Unique.create!(:uni开发者_如何学Goque_field => 'unique_value')
Unique.new(:unique_field => 'unique_value').should_not be_valid

Ideally, I'd like to get my nose out of the database for uniqueness validations. Any ideas how to go about doing that?


validates_uniqueness_of does not guarantee the absence of duplicate record insertions, because uniqueness checks on the application level are inherently prone to race conditionsmore. To get around this problem you might define unique index on on your unique field or write some workaround to have tests that don't depend on your database however I don't see any point in writing these tests. You'll just have some useless code in your app.


you can change the unique value dynamically by editing your factory to change every time you run test

for example

Factory.define :user do |f|
  f.sequence(:username) { |n| "foo#{n}" }
  f.password "foobar"
  f.password_confirmation { |u| u.password }
  f.sequence(:email) { |n| "foo#{n}@example.com" }
end

iHope it helpful , good luck

source : Railscasts Episode #158: Factory Girl

0

精彩评论

暂无评论...
验证码 换一张
取 消