samedi 15 juin 2019

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

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.

Aucun commentaire:

Enregistrer un commentaire