2011-07-01 49 views
3

我试图用RSpec测试Hour模型,即行为如同作用域的类方法'find_days_with_no_hours'。商业has_many与STI相关的时间。 find_days_with_no_hours需要通过Business对象调用,我无法弄清楚如何在RSpec测试中设置它。 我希望能够测试类似:测试has_many与RSpec的关联

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

我已经试过各种方法,如创建一个业务对象(比如说,Business.create),然后设置@ business.hours < < mock_model( BusinessHour,...,...),但这并不起作用。

这是如何正常完成的?

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 

回答

8

您不能通过mocks创建对象来测试一个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()(这会阻止数据库命中),然后使用查询数据库的方法。