使用 Shoulda-Matchers 和 FactoryGirl 测试 STI 关联

Testing STI Associations with Shoulda-Matchers & FactoryGirl

我在让简单的 STI shoulda-matcher 规范正确通过方面遇到了问题。

这是协会..

class User < ActiveRecord::Base
end

class Provider < ActiveRecord::Base
    belongs_to :practice_manager, class_name: 'User', foreign_key: :user_id
end

class PracticeManager < User
    has_many :providers
end

..还有我的工厂..

FactoryGirl.define do
    sequence(:email) { |n| "person#{n}@email.com" }
    sequence(:password) { |p| "thepassword123" }
    sequence(:password_confirmation) { |p| "thepassword123" }

    factory :user do
        email
        password
        password_confirmation
    end

    factory :practice_manager, parent: :user, class: 'PracticeManager' do
    end

    factory :provider_user, parent: :user, class: 'ProviderUser' do
    end

    factory :provider do
        sequence(:first_name) { |n| "Sally#{n}" }
        sequence(:last_name) { |n| "Harmon#{n}" }
        sequence(:npi) { |n| n.to_s.rjust(10, '0')}
        sequence(:sf_contact_ident) { |s| s.to_s.rjust(15, '0') }
        practice_manager
    end
end

..以及我想通过的考试。

require 'rails_helper'

RSpec.describe PracticeManager, type: :model do
    describe "Relationships" do
        it { should have_many(:providers).class_name('User').with_foreign_key(:user_id) }
    end
end

我发现的一件事是,如果我将 class_name: 'User', foreign_key: :user_id 添加到关联的 has_many 一侧,我可以通过测试,但恐怕这是误报。好像不太对。

非常感谢任何建议。

我认为你在混淆自己的联想。

要在您的 PracticeManager 模型中测试 has_many,您只需:

RSpec.describe PracticeManager, type: :model do
  describe "Relationships" do
    it { should have_many(:providers) }
  end
end

如果您想测试您的 Provider 模型,然后您需要额外的选项:

RSpec.describe Provider, type: :model do
  it { should belong_to(:practice_manager).class_name('User').with_foreign_key(:user_id) }
end