我正在尝试测试模型关联,但是当我运行测试时,它永远不会通过。
尝试按照文档进行操作,但没有成功。
我的实体故事与同一实体有3个关联:用户
class Story < ApplicationRecord
belongs_to :creator, class_name: 'User'
belongs_to :writer, class_name: 'User'
belongs_to :reviewer, class_name: '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'
测试:
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
尽管,当我运行测试时,我得到了:
Error:
StoryTest#test_: Story should belong to reviewer class_name => User. :
Mysql2::Error: Duplicate entry '' for key 'index_users_on_email'
已经尝试过,在Story模型上添加外键,结果仍然相同。
答案 0 :(得分:0)
我也在foreign_key
模型中添加了Story
,并且我的测试通过了:
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
此外,我的story_spec,rb
看起来像这样:
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