gpt4 book ai didi

ruby-on-rails - 如何在 RSpec 上包含 Rails Helpers

转载 作者:行者123 更新时间:2023-12-03 07:26:49 25 4
gpt4 key购买 nike

我试图包含一些帮助程序来使用 rspec 进行测试,但没有成功。

我做了什么:

在我的 spec 文件夹下创建了一个 support/helpers.rb 文件。

support/helpers.rb

module Helpers
include ActionView::Helpers::NumberHelper
include ActionView::Helpers::TextHelper
end

并尝试在 spec_helper.rb 中请求此文件。

# This file is copied to spec/ when you run 'rails generate rspec:install'
require 'rubygems'
require 'spork'
require 'support/helpers'

Spork.prefork do
.
.
end

这会产生以下错误:

/spec/support/helpers.rb:2:in `<module:Helpers>': uninitialized constant Helpers::ActionView (NameError)

我应该如何做这个助手才能与 Rspec 一起使用?

谢谢。

最佳答案

一旦 Rails 堆栈可用,我通常会包含此代码以要求我的 spec/support 子目录下的所有内容:

Spork.prefork do

# ...

Dir[Rails.root.join('spec', 'support', '**', '*.rb')].each { |f| require f }

RSpec.configure do |config|
config.include MyCustomHelper

# ...
end
end

请注意,这将在所有示例类型( Controller 、模型、 View 、助手等)中包含 MyCustomHelper。您可以通过传递 :type 参数来缩小范围:

config.include MyControllerHelper, :type => :controller

关于ruby-on-rails - 如何在 RSpec 上包含 Rails Helpers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9445410/

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