【问题标题】:Shoulda matcher fails with ActiveRecord::AssociationTypeMismatch when when testing uniqueness测试唯一性时,应该匹配器失败并显示 ActiveRecord::AssociationTypeMismatch
【发布时间】:2017-01-27 12:57:44
【问题描述】:

我正在开发一个 Rails5 API,我得到一个 ActiveRecord::AssociationTypeMismatch: 测试我的模型关联时出错。代码如下:

user.rb:

class User < ApplicationRecord
  acts_as_paranoid
  has_secure_password

  has_many :contracts
end

service.rb:

class Service < ApplicationRecord
  acts_as_paranoid

  has_many :contracts
end

合同.rb:

class Contract < ApplicationRecord
  acts_as_paranoid

  belongs_to :user
  belongs_to :service

  validates_presence_of :user
  validates :service, presence: true, uniqueness: { scope: :user_id }
end

contract_spec.rb:

RSpec.describe Contract, type: :model do
  let(:contract) { create(:contract) }

  describe 'Validations' do
    it { is_expected.to validate_presence_of(:user) }
    it { is_expected.to validate_presence_of(:service) }
    it { is_expected.to validate_uniqueness_of(:service).scoped_to(:user_id) }
  end

  describe 'Associations' do
    it { is_expected.to belong_to(:user) }
    it { is_expected.to belong_to(:service) }
  end
end

我的测试失败了:

1) Contract Validations should validate that :service is case-sensitively unique within the scope of :user_id
     Failure/Error: it { is_expected.to validate_uniqueness_of(:service).scoped_to(:user_id) }

     ActiveRecord::AssociationTypeMismatch:
       Service(#47073011870820) expected, got String(#47072966778980)

我似乎还有其他一些看起来像这样的问题,但没有一个可以解决这个问题。任何帮助将不胜感激。

【问题讨论】:

  • 我也面临同样的问题。这只发生在正在验证唯一性约束的关联对象上。我已经尝试了关联/关系名称(即user)以及外键(即user_id)——它们中的任何一个都没有运气。任何帮助将不胜感激。

标签: ruby-on-rails ruby activerecord rspec ruby-on-rails-5


【解决方案1】:

我遇到了同样的问题。一种解决方法是定义subject

describe 'Validations' do
  subject { create(:contract) }

  it { is_expected.to validate_presence_of(:user) }
  it { is_expected.to validate_presence_of(:service) }
  it { is_expected.to validate_uniqueness_of(:service).scoped_to(:user_id) }
end

来源:validates_uniqueness_of does not work when record is new and attribute is an association

【讨论】:

    猜你喜欢
    • 2016-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多