gpt4 book ai didi

ruby-on-rails - 测试 has_many 与 RSpec 的关联

转载 作者:行者123 更新时间:2023-12-01 09:36:36 24 4
gpt4 key购买 nike

我正在尝试使用 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 << 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

最佳答案

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

关于ruby-on-rails - 测试 has_many 与 RSpec 的关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6552721/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com