Reputation: 15967
I have a test like this:
require 'rails_helper'
RSpec.describe User, :type => :model do
it { should have_many(:assignments) }
it { should have_many(:roles).through(:assignments) }
end
Which returns this error:
Failure/Error: it { should have_many(:assignments) }
Expected User to have a has_many association called assignments (Assignment does not have a user_id foreign key.)
However my schema looks like this:
create_table "assignments", force: true do |t|
t.integer "user_id"
t.integer "role_id"
t.datetime "created_at"
t.datetime "updated_at"
end
My models look like this:
user.rb
require 'role_model'
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
validates :first_name, presence: true
validates :last_name, presence: true
validates :password, length: { minimum: 8 }
include RoleModel
roles_attribute :roles_mask
roles :admin, :super_admin, :user
has_many :assignments
has_many :roles, :through => :assignments
end
here is assignment.rb
class Assignment < ActiveRecord::Base
belongs_to :user
belongs_to :role
end
Any idea what I'm doing wrong here?
Upvotes: 1
Views: 571
Reputation: 15967
I changed nothing and the error simply went away a day later. I'm guessing something went out of sync for a bit but it's ok now.
Upvotes: 0
Reputation: 27747
Try your migration with the more-standard "references" (instead of just integer):
create_table "assignments", force: true do |t|
t.references "user", index: true
t.integer "role_id"
t.datetime "created_at"
t.datetime "updated_at"
end
Alternatively are you double-triple sure you've run your migrations?
Sometimes you need to run them for your tests too (if you're running an individual rspec spec rather than running all of them using rake). if in doubt: rake db:test:prepare
Upvotes: 3