Skip to content

Instantly share code, notes, and snippets.

@vmlinz
Last active December 15, 2015 07:32
Show Gist options
  • Save vmlinz/14ac6b01bf169ef4ae91 to your computer and use it in GitHub Desktop.
Save vmlinz/14ac6b01bf169ef4ae91 to your computer and use it in GitHub Desktop.
Rspec issue when testing user model
class User < ActiveRecord::Base
validates :auth_token, uniqueness: true
before_validation :downcase_email
before_create :generate_authentication_token!
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
def generate_authentication_token!
begin
self.auth_token = Devise.friendly_token
end while self.class.exists?(auth_token: auth_token)
end
private
def downcase_email
self.email = self.email.downcase if self.email.present?
end
end
require 'rails_helper'
RSpec.describe User, type: :model do
subject(:user) { FactoryGirl.create(:user) }
it { should respond_to(:auth_token) }
it { should validate_presence_of(:email) }
it { should validate_uniqueness_of(:email).case_insensitive }
it { should validate_confirmation_of(:password) }
it { should allow_value('[email protected]').for(:email) }
it { should validate_uniqueness_of(:auth_token) }
describe "authentication token should work" do
let!(:user) { FactoryGirl.create :user }
it "generates a unique token" do
Devise.stub(:friendly_token).and_return("auniquetoken123")
user.generate_authentication_token!
expect(user.auth_token).to eql "auniquetoken123"
end
it "generates another token when one already been taken" do
existing_user = FactoryGirl.create(:user, auth_token: "auniquetoken123")
user.generate_authentication_token!
expect(user.auth_token).not_to eql existing_user.auth_token
end
end
end
require 'rails_helper'
RSpec.describe User, type: :model do
before { @user = FactoryGirl.create(:user) }
subject { @user }
it { should respond_to(:auth_token) }
it { should validate_presence_of(:email) }
it { should validate_uniqueness_of(:email).case_insensitive }
it { should validate_confirmation_of(:password) }
it { should allow_value('[email protected]').for(:email) }
it { should validate_uniqueness_of(:auth_token) }
describe "#{generate_authentication_token!}" do
before { @user = FactoryGirl.create(:user) }
subject { @user }
it "generates a unique token" do
Devise.stub(:friendly_token).and_return("auniquetoken123")
@user.generate_authentication_token!
expect(@user.auth_token).to eql "auniquetoken123"
end
it "generates another token when one already been taken" do
existing_user = FactoryGirl.create(:user, auth_token: "auniquetoken123")
@user.generate_authentication_token!
expect(@user.auth_token).not_to eql existing_user.auth_token
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment