【问题标题】:Testing has_many association with RSpec测试 has_many 与 RSpec 的关联
【发布时间】:2011-07-01 20:04:10
【问题描述】:

我正在尝试使用 RSpec 测试 Hour 模型,即行为类似于范围的类方法“find_days_with_no_hours”。通过 STI 关联的业务 has_many Hours。 find_days_with_no_hours 需要通过业务对象调用,我不知道如何在 RSpec 测试中进行设置。 我希望能够测试类似的东西:

bh = @business.hours.find_days_with_no_hours
bh.length.should == 2

我尝试了各种方法,例如创建一个业务对象(例如,使用 Business.create),然后设置 @business.hours

这通常是怎么做的?

class Business < ActiveRecord::Base

  has_many :hours, :as => :hourable

end

class Hour < ActiveRecord::Base

  belongs_to :hourable, :polymorphic => true

  def self.find_days_with_no_hours
    where("start_time IS NULL")
  end

end

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 rspec rspec-rails


    【解决方案1】:

    您不能通过模拟创建对象来测试 arel 方法。 Arel 将直接进入数据库,并且看不到任何模拟或您在内存中创建的任何内容。我会抓住factory_girl,然后为自己定义一个小时工厂:

    Factory.define :hour do |f|
      f.start_time {Time.now}
    end
    
    Factory.define :unstarted_day, :parent => :hour do |f|
      f.start_time nil
    end
    

    然后在你的测试中......

    business = Factory.create(:business)
    business.hours << Factory.create(:unstarted_day)
    
    bh = business.hours.find_days_with_no_hours
    bh.length.should == 1
    

    但是, factory_girl 只是个人偏好设置已知状态,您可以轻松地使用 create 语句或固定装置,您的问题是尝试使用 mock_model() (防止数据库命中),以及然后使用查询数据库的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多