【问题标题】:has_many and belongs_to assertion in MiniTest using Mongoid使用 Mongoid 在 MiniTest 中的 has_many 和 belongs_to 断言
【发布时间】:2013-04-27 12:55:19
【问题描述】:

我使用 Mongoid 作为数据库,我有两个模型,如下所示。我不能断言 has_many 和 belongs_to 关系。我可以在 MiniTest 中断言什么关系。

Event.rb

class Event
  include Schizo::Data
  include Mongoid::Document

  field :name
  field :start_at
  field :finish_at
  field :status
  field :location

  has_many :participations
end

参与.rb

class Participation
  include Mongoid::Document

  belongs_to :event
  belongs_to :participant

end

【问题讨论】:

    标签: ruby-on-rails ruby minitest


    【解决方案1】:

    这就是我使用 Minitest 在 Rails 中测试 has_many 关联的方法,它也应该适用于您。将其放入Event 的模型测试文件中:

      test 'contains a has_many relationship to participations' do
        expected = [
          :participations
        ].sort
    
        actual = Event.reflect_on_all_associations(:has_many).map(&:name).sort
    
        assert_equal(expected, actual)
      end
    

    这就是我在 Rails 中使用 Minitest 测试 belongs_to 关联的方法,它也应该适用于您。将其放入Participation 的模型测试文件中:

      test 'contains a belongs_to relationship to some models' do
        expected = [
          :event,
          :participant
        ].sort
    
        actual = Participation.reflect_on_all_associations(:belongs_to).map(&:name).sort
    
        assert_equal(expected, actual)
      end
    

    仅供参考:无论数据库实现如何,这都应该有效。

    【讨论】:

      【解决方案2】:

      考虑为此使用mongoid-minitest gem。查看详情here

      您的规格将如下所示:

      describe Event do
        subject { Event }
      
        it { must have_many(:participations) }
      end
      
      describe Participation do
        subject { Participation }
      
        it { must belong_to(:participations) }
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-09-26
        • 1970-01-01
        • 2020-04-07
        • 1970-01-01
        • 2013-11-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多