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
精彩评论