I am writing tests for my models and came across an error I can't seem to resolve. I'm using rspec and Fabricator. Things work fine when being tested in isolation but when I try to test for associations I get an ActiveModel::MissingAttributeError.
models/user.rb
class User < ApplicationRecord
...
validates :email, uniqueness: true, presence: true
belongs_to :company, required: false
end
models/company.rb
class Company < ApplicationRecord
validates :organisation_number, uniqueness: true, presence: true
has_many :users, dependent: :destroy
end
schema
create_table "companies", force: :cascade do |t|
t.string "organisation_number"
...
end
create_table "users", id: :serial, force: :cascade do |t|
t.string "email", default: "", null: false
...
t.bigint "company_id"
t.index ["company_id"], name: "index_users_on_company_id"
...
end
fabricators/user_fabricator.rb
Fabricator :user do
email { Faker::Internet.email }
password '123456'
confirmed_at Time.now
end
fabricators/company_fabricator.rb
Fabricator :company do
organisation_number { Faker::Company.swedish_organisation_number }
end
spec/user_spec.rb (first test passes, the second fails)
describe User do
context '#create' do
it 'Creates a user when correct email and password provided' do
user = Fabricate(:user)
expect(user).to be_valid
end
it 'Lets assign a company to user' do
company = Fabricate(:company)
expect(Fabricate.build :user, company: company).to be_valid
end
end
end
I also tried adding a company straight to the User fabricator, like so (which seems to me like a correct implementation of the documentation):
Fabricator :user do
email { Faker::Internet.email }
password '123456'
confirmed_at Time.now
company
end
and the other way around, adding users to the Company fabricator, like so:
Fabricator :company do
organisation_number { Faker::Company.swedish_organisation_number }
users(count: 3) { Fabricate(:user) }
end
but both approaches left me with the same error:
User#create Lets assign a company to user
Failure/Error: company = Fabricate(:company)
ActiveModel::MissingAttributeError: can't write unknown attribute 'company_id'
Any suggestions on what I'm doing wrong?