【发布时间】:2015-10-29 22:44:58
【问题描述】:
我创建了一个 really simple Rails app 来演示我的问题。
这是一个干净的 Rails 4.2 应用程序,其中一个模型如下所示:
# charigfy.rb
module Chargify
class Webhook
def self.process
puts "Hello world"
end
end
end
该文件基本上是重新打开chargify gem中的Chargify模块并重新打开Webhook类以添加类方法process。
我添加了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
当我使用 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
现在我可以通过更改模型使其不会重新打开模块并以不同的命名空间来完成这项工作,或者我可以在规范中明确地require 'chargify',但我觉得有一个更好的解决方案。
可能它不起作用,因为在 describe Chargify::Webhook do 它是从 gem 而不是从模型加载类,因为它在模型之前的 gem 文件中找到了适当的类。
最好的或最Rails-y的方法是什么?
【问题讨论】:
-
大概您将 Chargify 模块包含在其他类中...您可以实例化它来测试过程吗?或者创建一个假模型,在其中包含您想要的充电方式......并使用它?
-
好吧,我有一个 ChargifyController,它接收 webhook,然后以该 webhook 主体作为参数调用
Chargify::Webhook.process。我已经对 ChargifyController 进行了测试,但我也希望能够保留单元规格。 -
第二个建议也是如此:在您的规范中创建一个包含 Chargfy 模块的类并使用它进行测试。
标签: ruby-on-rails ruby rspec gem autoload