简体   繁体   English

模型未在Rails应用程序的RSpec测试中加载

[英]Model not getting loaded in rspec tests in Rails app

I've created a really simple Rails app that demonstrates my question. 我创建了一个非常简单的Rails应用程序来演示我的问题。

It's a clean Rails 4.2 app with one model that looks like this: 这是一个干净的Rails 4.2应用,其中的一个模型如下所示:

# charigfy.rb

module Chargify
  class Webhook
    def self.process
      puts "Hello world"
    end
  end
end

The file is basically re-opening the Chargify module in the chargify gem and the re-opening the Webhook class in order to add a class method, process . 该文件基本上是重新打开chargify gem中的Chargify模块,并重新打开Webhook类,以便添加类方法process

I've added the chargify_api_ares gem and then added a simple model spec, that looks like this: 我添加了chargify_api_ares gem,然后添加了一个简单的模型规范,如下所示:

require_relative '../test_helper'

describe Chargify::Webhook do
  context "testing" do
    it "should work" do
      Chargify::Webhook.process
    end
  end
end

When I run the spec using bundle exec rspec test/models I get this output: 当我使用bundle exec rspec test/models运行规范时,得到以下输出:

Failures:

  1) Chargify::Webhook testing should work
     Failure/Error: Chargify::Webhook.process
     NoMethodError:
       undefined method `process' for Chargify::Webhook:Class
     # ./test/models/chargify_spec.rb:6:in `block (3 levels) in <top (required)>'

Finished in 0.00121 seconds (files took 3.3 seconds to load)
1 example, 1 failure

Failed examples:

rspec ./test/models/chargify_spec.rb:5 # Chargify::Webhook testing should work

Now I can make this work by either changing the model so that it doesn't re-open the module and is namespaced differently, or I can explicitly require 'chargify' in the spec, but I feel like there's a better solution. 现在,我可以通过更改模型以使其不重新打开模块并以不同的命名空间进行工作,或者可以在规范中明确require 'chargify' ,但我觉得有更好的解决方案。

Presumably it's not working because in describe Chargify::Webhook do it's loading the class from the gem and not from the model, seeing as it finds the appropriate class in the gem's files before the model. 大概是行不通的,因为在describe Chargify::Webhook do它是从gem而不是从模型加载类,因为它在模型之前在gem的文件中找到了合适的类。

What's the best or most Rails-y way of making this work? 进行这项工作的最佳或最Rails-y方法是什么?

IMHO the best way to patch/extend Ruby classes that are loaded by Rails is to move your code out of app/models (or lib ) and into an initializer. 恕我直言,修补/扩展Rails加载的Ruby类的最好方法是将代码移出app/models (或lib )并移入初始化程序。 Rails executes initializers as one of the final steps when booting up, so you are less likely to run into load order issues. Rails在启动时将初始化程序作为最后的步骤之一,因此您不太可能遇到加载顺序问题。

The main drawback of initializers is that you must restart the server to apply changes, which is less convenient than reloading in development. 初始化程序的主要缺点是必须重新启动服务器才能应用更改,这比在开发中重新加载不方便。

See the docs for more about Rails initialization and configuration . 请参阅文档以获取有关Rails 初始化配置的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM