Testing multiple associations with shoulda, should belong to using foreign key

238 views Asked by At

I'm trying to test model associations, but when I run the test, it never passes.

Tried following the documentation, but had no success.

My entity Story has 3 associations with the same entity: User

class Story < ApplicationRecord
  belongs_to :creator, class_name: 'User'
  belongs_to :writer, class_name: 'User'
  belongs_to :reviewer, class_name: 'User'
end

Associations defined on the User end:

has_many :created_stories, class_name: 'Story',
    foreign_key: 'creator_id'
  has_many :written_stories, class_name: 'Story',
    foreign_key: 'writer_id'
  has_many :reviewed_stories, class_name: 'Story',
    foreign_key: 'reviewer_id'

Test:

class StoryTest < ActiveSupport::TestCase
  should belong_to(:creator).class_name('User').with_foreign_key('creator_id')
  should belong_to(:writer).class_name('User').with_foreign_key('writer_id')
  should belong_to(:reviewer).class_name('User').with_foreign_key('reviewer_id')
end

Although, when I run the test, I get:


Error:
StoryTest#test_: Story should belong to reviewer class_name => User. :
Mysql2::Error: Duplicate entry '' for key 'index_users_on_email'

Already tried, adding the foreign key on Story model, still had the same results.

1

There are 1 answers

0
Violeta On

I added the foreign_key in the Story model too, and my tests passed:

class Story < ApplicationRecord
  belongs_to :creator, class_name: 'User', foreign_key: "creator_id"
  belongs_to :writer, class_name: 'User', foreign_key: "writer_id"
  belongs_to :reviewer, class_name: 'User', foreign_key: "reviewer_id"
end

Also, my story_spec,rb looks like this:

require 'rails_helper'

RSpec.describe Story, type: :model do
  context "associations" do
    it { should belong_to(:creator).class_name('User').with_foreign_key('creator_id') }
    it { should belong_to(:writer).class_name('User').with_foreign_key('writer_id') }
    it { should belong_to(:reviewer).class_name('User').with_foreign_key('reviewer_id') }
  end
end