ruby on rails - Why does this spec of my model's uniqueness validation fail when it should pass? -
i learning testing rspec. not working tests.
my model:
class user < activerecord::base has_secure_password # validation macros validates_presence_of :name, :email validates_uniqueness_of :email, case_sensitive: false end
my factory:
factorygirl.define factory :user name "joe doe" email "joe@example.com" password_digest "super_secret_password" end end
and spec:
require 'rails_helper' rspec.describe user, type: :model user = factorygirl.build(:user) 'has valid factory' expect(factorygirl.build(:user)).to be_valid end { is_expected.to respond_to(:name) } { is_expected.to respond_to(:email) } { is_expected.to respond_to(:password) } { is_expected.to respond_to(:password_confirmation) } { expect(user).to validate_presence_of(:name) } { expect(user).to validate_presence_of(:email) } { expect(user).to validate_presence_of(:password) } { expect(user).to validate_uniqueness_of(:email).case_insensitive } end
i expected test pass. result:
failures:
1) user should validate :email case-insensitively unique failure/error: { expect(user).to validate_uniqueness_of(:email).case_insensitive }
user did not validate :email case-insensitively unique. record provided not created, failed following validation errors: * name: ["can't blank"] # ./spec/models/user_spec.rb:18:in `block (2 levels) in <top (required)>'
finished in 0.34066 seconds (files took 1.56 seconds load) 9 examples, 1 failure
failed examples:
rspec ./spec/models/user_spec.rb:18 # user should validate :email case-insensitively unique
what missing?
update
i think bug: https://github.com/thoughtbot/shoulda-matchers/issues/830
your variable set once tests
when write code like:
rspec.describe user, type: :model user = factorygirl.build(:user) end
you aren't building new user each time run new spec. likewise, using #let wrong approach, because it memoizes variable between tests. instead, need use rspec before#each block. example:
describe user before @user = factorygirl.build :user end # specs end
if have tests persisting user database, , if have disabled rollback or database cleaning between tests, defined factory (as written) fail uniqueness validation. in such cases, may want try:
user.delete_all
in test, or otherwise cleaning database between tests.- using factorygirl sequences or faker gem ensure user attributes unique.
Comments
Post a Comment