测试 has_many 与 RSpec 的关联 [英] Testing has_many association with RSpec

查看:39
本文介绍了测试 has_many 与 RSpec 的关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 RSpec 测试 Hour 模型,即行为类似于范围的类方法find_days_with_no_hours".通过 STI 关联的业务有_许多小时.find_days_with_no_hours 需要通过业务对象调用,我不知道如何在 RSpec 测试中设置它.我希望能够测试以下内容:

I'm trying to test the Hour model with RSpec, namely the class method 'find_days_with_no_hours' that behaves like a scope. Business has_many Hours associated through STI. find_days_with_no_hours needs to be called through a Business object and I can't figure out how to set this up in the RSpec test. I want to be able to test something like:

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

我尝试了各种方法,例如创建一个 Business 对象(例如,使用 Business.create),然后设置 @business.hours <<mock_model(BusinessHour, ..., ..., ...) 但这不起作用.

I've tried various approaches, like creating a Business object (with, say, Business.create), then setting @business.hours << mock_model(BusinessHour, ..., ..., ...) but that doesn't work.

这通常是如何完成的?

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

推荐答案

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

You can't test an arel method by creating the object via mocks. Arel is going to go straight into the database, and not see any mocks or anything that you've created in memory. I would grab factory_girl and then define an hour factory for yourself:

Factory.define :hour do |f|
  f.start_time {Time.now}
end

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

然后在你的测试中...

And then in your test...

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()(这可以防止数据库命中),然后使用查询数据库的方法.

However, factory_girl is just a personal preference for setting up known state, you can just as easily use create statements or fixtures, the problem for you was trying to use mock_model() (which prevents a database hit), and then using a method that queries the database.

这篇关于测试 has_many 与 RSpec 的关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆