Rails Shoulda Matcher - 测试模块化模型的问题

时间:2018-01-21 16:44:08

标签: ruby-on-rails rspec

我正在使用RSpec和Shoulda-Matchers来测试我的模型。

我理解如何测试模型是否像这样

class Headquarter < ApplicationRecord
  has_many :branches
end

class Branch < ApplicationRecord
  belongs_to :headquarter
end

我可以写一个像这样的应该匹配的人:

RSpec.describe Headquarter, type: :model do
  it { should have_many(branches)}
end

RSpec.describe Branch, type: :model do
  it { should belong_to(:headquarter)}
end

我的问题

但是当我使用模块化模型时出现问题,例如Company::HeadquarterCompany::Branch

我尝试使用此代码:

RSpec.describe Company::Headquarter, type: :model do
  it { should have_many(:company_branches)}
end

但它给了我一个错误,似乎它不能将模型识别为模块化。

Failure/Error: it { should have_many(:company_branches)}
   Expected Company::Headquarter to have a has_many association called company_branches (Company::Branch does not have a headquarter_id foreign key.)

当我期待 headquarter_id时,请注意错误中的company_headquarter_id。这就是为什么它不识别ID。

1 个答案:

答案 0 :(得分:0)

在查看代码文档之后,我发现了两个有用的代码片段:

对于自定义class_name

  # ##### class_name
  #
  # Use `class_name` to test usage of the `:class_name` option. This
  # asserts that the model you're referring to actually exists.
  #
  #     class Person < ActiveRecord::Base
  #       has_many :hopes, class_name: 'Dream'
  #     end
  #
  #     # RSpec
  #     RSpec.describe Person, type: :model do
  #       it { should have_many(:hopes).class_name('Dream') }
  #     end
  #
  #     # Minitest (Shoulda)
  #     class PersonTest < ActiveSupport::TestCase
  #       should have_many(:hopes).class_name('Dream')
  #     end

对于自定义外键:

  # ##### with_foreign_key
  #
  # Use `with_foreign_key` to test usage of the `:foreign_key` option.
  #
  #     class Person < ActiveRecord::Base
  #       has_many :worries, foreign_key: 'worrier_id'
  #     end
  #
  #     # RSpec
  #     RSpec.describe Person, type: :model do
  #       it { should have_many(:worries).with_foreign_key('worrier_id') }
  #     end
  #
  #     # Minitest (Shoulda)
  #     class PersonTest < ActiveSupport::TestCase
  #       should have_many(:worries).with_foreign_key('worrier_id')
  #     end

如何解决

模型

如果您有相关提及的型号:

Company::Headquarter,添加 foreign_key 标记

class Company::Headquarter < ApplicationRecord
  has_many :company_branches, :class_name => 'Company::Branch', foreign_key: 'company_headquarter_id'

end

Company::Branch

class Company::Branch < ApplicationRecord
  belongs_to :company_headquarter, :class_name => 'Company::Headquarter'
end

对于RSpec

headquarter_spec.rb,请注意 class_name with_foreign_key 功能。

RSpec.describe Company::Headquarter, type: :model do
  it { should have_many(:company_branches).class_name('Company::Branch').with_foreign_key('company_headquarter_id')}
end

来源:Shoulda-Matchers, association matcher Documentation