ruby-on-railsruby-on-rails-4rspecmodel-associationsfabrication-gem

Rails 4 - error creating associations through Fabricator in Rspec tests


Ok, i am trying to use Fabricator with my Rspec tests to mock some data for the tests. I'm having some trouble with a belongs_to association, however. Here's what i have so far:

user.rb

class User < ActiveRecord::Base
  authenticates_with_sorcery!

  belongs_to :organization

  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

  validates_presence_of :full_name
  validates_presence_of :email
  validates_uniqueness_of :email, on: :create
  validates_format_of :email, with: VALID_EMAIL_REGEX, on: :create
  validates_presence_of :password, on: :create
  validates_confirmation_of :password
end

organization.rb

class Organization < ActiveRecord::Base
  authenticates_with_sorcery!

  has_many :users, dependent: :destroy

  accepts_nested_attributes_for :users, :allow_destroy => true

  validates_presence_of :name
end

integration_spec.rb

require 'rails_helper'

describe "Shopping Cart Requests" do
  let!(:user) { Fabricate(:user) }

  before(:each) do
    login_user_post("admin@example.com", "password")
  end

  context "when I visit the shopping cart" do
    it " show the logged in users' cart items " do
      #Test stuff
    end
  end
end

user_fabricator.rb

Fabricator(:user) do
  organization { Fabricate(:organization) }
  email { "admin@example.com" }
  password { "password" }
  full_name { Faker::Name.name }
  is_admin { true }
  salt { "asdfghjkl123456789" }
  crypted_password { Sorcery::CryptoProviders::BCrypt.encrypt("secret", "asdasdastr4325234324sdfds") }
  activation_state { 'active' }
end

organization_fabricator.rb

Fabricator(:organization) do
  name { Faker::Company.name }
  website { Faker::Internet.url }
  description { Faker::Lorem.paragraph }
  access_code { Faker::Internet.password(10, 20) }
end

Here's the error i am getting when running the test:

Failure/Error: let!(:user) { Fabricate(:user) }
     NoMethodError:
       undefined method `crypted_password' for #<Organization:0x007f80ee0a44e0>
     # ./spec/features/integration_spec.rb:4:in `block (2 levels) in <top (required)>'

Solution

  • You have authenticates_with_sorcery! in your Organization app.

    If you don't intend to authenticate Organization, you should remove that line.

    Cheers