【问题标题】:Shoulda belongs_to with class_name and foreign_key应该使用 class_name 和 foreign_key 的 belongs_to
【发布时间】:2012-09-02 08:15:30
【问题描述】:

我知道您可以使用 Shoulda 轻松测试归属关系:

describe Dog dog
  it { should belong_to(:owner) }
end

是否可以使用Shouda 测试更复杂的belongs_to 关系?像这样的:

class Dog < ActiveRecord::Base
  belongs_to :owner, :class_name => "Person", :foreign_key => "person_id"
end

【问题讨论】:

    标签: ruby-on-rails rspec shoulda


    【解决方案1】:

    你应该可以使用:

    it { should belong_to(:owner).class_name('Person') }
    

    Shoulda 的 belong_to 匹配器始终从关联中读取 foreign_key 并测试它是否是有效的字段名称,因此您无需再做任何事情。

    (参见Shoulda::Matchers::ActiveRecord::AssociationMatcher#foreign_key_exists? 和相关方法)

    【讨论】:

      【解决方案2】:

      现在可以测试自定义外键:

      it { should belong_to(:owner).class_name('Person').with_foreign_key('person_id') }
      

      见:https://github.com/thoughtbot/shoulda-matchers/blob/master/lib/shoulda/matchers/active_record/association_matcher.rb#L122

      【讨论】:

        【解决方案3】:

        我知道我参加聚会有点晚了,所以我的解决方案可能需要shoulda 的最新版本。

        在撰写本文时,我在 v 2.4.0

        我的规范中不需要class_namewith_foreign_key

        确保您在模型中指定了class_nameforeign_key

        # model.rb:  
        belongs_to :owner, inverse_of: :properties, class_name: "User", foreign_key: :owner_id
        
        # spec.rb:  
        it { should belong_to(:owner) }
        

        结果输出:

        should belong to owner
        

        【讨论】:

          【解决方案4】:

          如果关联喜欢

          belongs_to :custom_profile, class_name: 'User', foreign_key: :custom_user_id, optional: true
          

          那么rspec应该是

          it { should belong_to(:custom_profile).class_name('User').with_foreign_key('custom_user_id').optional }
          

          这里optional用于可选:true,如果您的关联中不需要可选true,您也可以将其删除

          【讨论】:

            【解决方案5】:

            所以should-matchers README 的细节非常简单,只是提供了一些示例。我发现类的 RDoc 中有更多信息,如果是 belongs_to,请查看 association_matcher.rb。第一种方法是为belongs_to 使用Rdoc

              # Ensure that the belongs_to relationship exists.
              #
              # Options:
              # * <tt>:class_name</tt> - tests that the association makes use of the class_name option.
              # * <tt>:validate</tt> - tests that the association makes use of the validate
              # option.
              #
              # Example:
              #   it { should belong_to(:parent) }
              #
              def belong_to(name)
            

            所以belongs_to 只支持:class_name:validate 的测试。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2013-08-11
              • 1970-01-01
              • 2017-04-29
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多