如何在RSpec中包含几个模块?

Ale*_*pov 7 ruby rspec module ruby-on-rails code-organization

我不确定将几个模块包含在RSpec中的方法,所以让我来描述一下我的情况.

app/helpers我有两个文件与助手,包含模块ApplicationHelperMailersHelper.虽然这些是我在视图和邮件中使用的视图助手,但我也在我的测试中使用了一些方法,所以它们必须在describe子句中可访问.

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

另外,我有以下代码:

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

def helper
  Helper.instance
end
Run Code Online (Sandbox Code Playgroud)

它的目的是使测试中的视图助手可用.目前,此代码位于Helper包装器方法之前的模块中,因为它们使用该Helper.instance方法.

我有三个邮件,我想测试.那么如何在测试中使所有这些东西都可以访问?

选项1

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

require 'spec_helper'

describe MyMailer do
  include ApplicationHelper
  include MailersHelper
  include Helpers
  ...
end
Run Code Online (Sandbox Code Playgroud)

选项2

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

require 'spec_helper'

module Helpers
  include MailersHelper
  include ApplicationHelper
  ...

end

RSpec.configure { |c| c.include Helpers }
Run Code Online (Sandbox Code Playgroud)

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

选项3

和上面一样但不是包括ApplicationHelperMailersHelperHelpers,我这样做:

RSpec.configure do |c| 
  c.include Helpers
  c.include ApplicationHelper
  c.include MailersHelper
end
Run Code Online (Sandbox Code Playgroud)

我很困惑的是:

  1. 我在一个单独的文件(helpers.rb)中执行RSpec.configure部分,我require_relative在我的邮件程序规范中.所以这意味着这些模块只能用于我的邮件规格,而不是整套服装,对吧?(如果我在spec_helper.rb中这样做的话会是这种情况).

  2. 组织方法的最佳实践是什么,它们不是视图助手,而是在几个类(主要是控制器或邮件程序)之间共享的助手.它们应该如何命名,它们应该放在哪里?

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

Ada*_*sek 7

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

RSpec.configure do |config|
  config.include MailersHelper, type: :mailer
end
Run Code Online (Sandbox Code Playgroud)

spec/mailers现在的任何规格将自动包含MailersHelper

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

RSpec.describe FooConstant, type: :mailer do
  # ... etc
end
Run Code Online (Sandbox Code Playgroud)

如果规范不存在,spec/mailers但您希望将其视为一种规范。