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

时间:2015-09-30 21:56:11

标签: ruby-on-rails rspec factory-bot shoulda sti

我遇到了一个简单的STI应该匹配规范正确传递的问题。

以下是协会..

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方面,我可以通过测试,但我担心这是误报。这似乎不对。

非常感谢任何建议。

1 个答案:

答案 0 :(得分:1)

我认为你正在混淆你的社团。

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

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

如果您想测试您的提供商型号,那么您需要额外的选项:

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