使用已声明的Rails模型

时间:2012-06-21 07:47:05

标签: ruby-on-rails testing dependency-injection specifications isolation

为(快速)测试目的声明一个类很棒:

require 'fast_helper'
require 'site_search'

class Post; end # This allows not to load the whole Rails env

describe SiteSearch do
  it "searches on posts" do
    Post.stub_chain(:scoped, :by_term).with("ruby").and_return ["post1", "post2"]
    SiteSearch.by_term("ruby").should == ["post1", "post2"]
  end
end

问题在于,当运行整套规范时,它似乎会破坏rails模型的自动加载。

以前声明类时,模型不再加载。

4 ways of injecting the unloaded dependencies

  1. 声明课程(如此处的示例)
  2. 设置/删除const
  3. 存根包装方法
  4. 实际加载
  5. 我只想使用第一个。

    问题:保持相同的规格结构,即使已经声明了类,我如何告诉rails实际加载模型?

1 个答案:

答案 0 :(得分:1)

为了使您的空类抢占技巧起作用,您必须设置应用config.cache_classes = false,因此除非您致电

,否则不会发生急切加载
Rails.application.eager_load!

运行整个测试套件时,您需要确保类预加载,然后空重新定义应该没有效果。

现在的问题是如何控制它只在调用完整的测试套件时运行。诚实的答案是我不知道,但你肯定可以从环境中控制它。在您的rspec助手中的某个位置初始化rails,将其更新为:

ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
Rails.application.eager_load! unless ENV["FORCE_EAGER_LOAD"].blank?

然后在完整套件上调用rspec:

FORCE_EAGER_LOAD=t rspec
相关问题