【问题标题】:Rspec mocking for testing queries of an associated record用于测试关联记录查询的 Rspec 模拟
【发布时间】:2012-11-06 20:43:45
【问题描述】:

我有以下型号:

class Kueue < ActiveRecord::Base
    attr_accessible :name, :user_id

    belongs_to :user
    has_and_belongs_to_many :photos

    scope :empty, includes(:photos).where{ photos.id.eq(nil) }
    scope :with_photos, includes(:photos).where{ photos.id.not_eq(nil) }
end

我想为示波器编写规范,以确保它们可靠地工作。我的问题是如何处理Photo 模型。照片上有很多验证,例如它们必须属于User。所以,我可以为这些查询编写一个工作规范,如下所示:

describe "queries" do
    before :each do
        @empty = Fabricate(:kueue)
        @full = Kueue.new :name => "Full Queue"
        @full.photos << Fabricate(:photo)
        @full.save
    end

    it "should find empty queues" do
        Kueue.empty.should_not include(@full)
    end

    it "should find queues with photos" do
        Kueue.with_photos.should_not include(@empty)
    end
end

但是,您可以想象这是 sloooow。这会对数据库进行大量调用。 (1) 制作两个 kueues,(2) 制作一张照片,(3) 制作一个拥有该照片的用户……等等。

这似乎是一个很简单的问题,我只需要一张照片和一个 kue 之间的连接记录,我可以很快地测试这个。那么,您将如何模拟这种交互,以便更快、更好地进行测试呢?

PS:我使用的是 Rails 3.2.8,Squeel(因此是查询语法),我的模型称为 Kueue,因为 Queue 是 Rails 中的保留字 :)

【问题讨论】:

    标签: ruby-on-rails rspec refactoring tdd bdd


    【解决方案1】:

    我认为在范围的上下文中模拟是没有意义的。

    范围基本上是数据库查询,您要确保它们与数据库一起使用。

    所以如果你的问题是测试性能,那么我建议:

    • 在这种情况下试用固定装置

    • 跳过模型验证,以减少所需的模型

    【讨论】:

    • Phoet,非常感谢您的建议。我不得不稍微摆弄一下我的回调,以便在测试环境中无需验证即可保存,但这天文数字提高了我的测试速度。大赞!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多