gpt4 book ai didi

ruby-on-rails - 如何在 RSpec 中包含多个模块?

转载 作者:数据小太阳 更新时间:2023-10-29 07:06:38 25 4
gpt4 key购买 nike

我不确定将几个模块包含到RSpec中的方式,所以让我描述一下我的情况。

app/helpers 下,我有两个带有助手的文件,包含模块 ApplicationHelperMailersHelper。尽管这些是我在我的 View 和邮件中使用的 View 助手,但我也在我的测试中使用了它们的一些方法,因此它们必须可以在 describe 子句中访问。

app/spec/mailers 下,我还有一个文件,包含模块 Helpers。该模块包含仅在测试中使用的方法(主要是长期期望的包装方法)。

此外,我还有以下代码:

class Helpers
include Singleton
include ActionView::Helpers::UrlHelper
include ActionView::Helpers::NumberHelper
end

def helper
Helper.instance
end

它的目的是使 View 助手在测试中可用。目前,这段代码驻留在包装器方法之前的 Helper 模块中,因为它们使用 Helper.instance 方法。

我有三个邮件程序,我想测试它们。那么我如何让所有这些东西在测试中都可以访问呢?

选项 1

在每个邮件程序规范中直接使用 include 如下:

require 'spec_helper'

describe MyMailer do
include ApplicationHelper
include MailersHelper
include Helpers
...
end

选项 2

在文件 helpers.rb 中,我这样做:

require 'spec_helper'

module Helpers
include MailersHelper
include ApplicationHelper
...

end

RSpec.configure { |c| c.include Helpers }

并且在每个邮件程序规范中我使用 require_relative './helpers'

选项 3

和上面一样,但不是在 Helpers 中包含 ApplicationHelperMailersHelper,我这样做:

RSpec.configure do |c| 
c.include Helpers
c.include ApplicationHelper
c.include MailersHelper
end

我很困惑的是:

  1. 我在一个单独的文件 (helpers.rb) 中执行 RSpec.configure 部分,我在我的邮件规范中require_relative。所以这意味着这些模块将仅适用于我的邮件规范,而不适用于整个套装,对吗? (如果我在 spec_helper.rb 中这样做,情况就会如此)。

  2. 组织方法的最佳实践是什么,这些方法不是 View 帮助程序,而是在多个类(主要是 Controller 或邮件程序)之间共享的帮助程序。应该怎么命名,放在哪里?

持续自动加载对我来说真的是一个很难的话题 - 有时你可以直接获得一个模块/类而你不需要做任何事情(但这可能取决于你的文件/模块的确切命名),有时你必须require 它或 relative_require 它,但你必须小心你在哪里做这件事,否则它会变得全局可用,有时你有一种特殊的方式来包含诸如使用 RSpec.configure...哦,男孩!

最佳答案

这应该在 spec_helper.rb 中完成。您可以根据规范类型有条件地包含模块。

RSpec.configure do |config|
config.include MailersHelper, type: :mailer
end

spec/mailers 中的任何规范现在都将自动包含 MailersHelper

您可以通过以下方式手动触发此操作

RSpec.describe FooConstant, type: :mailer do
# ... etc
end

如果规范不在 spec/mailers 中,但您想像对待规范一样对待它。

关于ruby-on-rails - 如何在 RSpec 中包含多个模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24796960/

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