Reputation: 54979
I am trying to Test the User Model Spec for User Creation
factories/users.rb
FactoryGirl.define do
factory :user do
first_name {Faker::Name.first_name}
last_name {Faker::Name.last_name}
email {Faker::Internet.email}
username {Faker::Internet.user_name}
password {Faker::Internet.password}
end
end
specs/models/user_spec.rb
require 'rails_helper'
describe User, :type => :model do
context "valid Factory" do
it "has a valid factory" do
expect(build(:user)).to be_valid
end
end
context "validations" do
before { create(:user) }
context "presence" do
it { should validate_presence_of :first_name }
it { should validate_presence_of :last_name }
it { should validate_presence_of :email }
it { should validate_presence_of :encrypted_password }
end
context "uniqueness" do
it { should validate_uniqueness_of :email }
it { should validate_uniqueness_of :username }
end
end
end
I am using Devise for the USer creation. But i am ending up with the following Test Failure
User
valid Factory
has a valid factory
validations
presence
should require first_name to be set
should require last_name to be set
should require email to be set
should require encrypted_password to be set (FAILED - 1)
uniqueness
should require case sensitive unique value for email
should require case sensitive unique value for username
Failures:
1) User validations presence should require encrypted_password to be set
Failure/Error: it { should validate_presence_of :encrypted_password }
Expected errors to include "can't be blank" when encrypted_password is set to nil,
got no errors
# ./spec/models/user_spec.rb:18:in `block (4 levels) in <top (required)>'
Finished in 0.98827 seconds (files took 6.61 seconds to load)
7 examples, 1 failure
Failed examples:
rspec ./spec/models/user_spec.rb:18 # User validations presence should require encrypted_password to be set
Am assuming that the encrypted_password
will be auto generated by Devise on trying to create the user.
Upvotes: 0
Views: 7067
Reputation: 102249
Devise does not actually validate the encrypted password since it is created dynamically after validation if the password is "dirty" (changed).
You don't actually need to test the encrypted password in that way since it is an implementation detail. You can test that Database authenticable is working properly by doing something like:
it 'is database authenticable' do
user = User.create(
email: '[email protected]',
password: 'password123',
password_confirmation: 'password123'
)
expect(user.valid_password?('password123')).to be_truthy
end
But the actual value of the test is pretty low. Instead with Devise you you may want to focus on some end-to-end tests (feature specs) where you test the user path of signing up and then logging in.
Upvotes: 6
Reputation: 9969
I would suggest you only test those validations you added, you do not need to test validations added by devise since they are already been tested.
Upvotes: 1