【问题标题】:Testing multiple associations with shoulda, should belong to using foreign key用should测试多个关联,应该属于使用外键
【发布时间】:2019-06-15 19:21:02
【问题描述】:

我正在尝试测试模型关联,但是当我运行测试时,它从未通过。

按照文档尝试,但没有成功。

我的实体故事与同一实体有 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模型上加外键,结果还是一样。

【问题讨论】:

  • 错误发生在 3 个关联上,而不仅仅是审阅者

标签: ruby-on-rails testing shoulda


【解决方案1】:

我也在Story 模型中添加了foreign_key,并且我的测试通过了:

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

【讨论】:

    猜你喜欢
    • 2015-11-12
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 2014-08-29
    • 1970-01-01
    相关资源
    最近更新 更多