如何在 Rails 中的每个规范中包含共享上下文

Dam*_*iev 1 rspec ruby-on-rails rspec-rails

我有一个共享的上下文:

shared_context :current_country do
  let!(:country) { create :country, slug: "kw" } unless Country.find_by(slug: "kw").present?
end
Run Code Online (Sandbox Code Playgroud)

我需要访问country每个规范中的变量。

要使用它,我需要include_context :current_country在每个规范文件中使用它。是否可以避免在每个规范文件中包含这一行,而是将上下文配置为在任何地方都可用?

eug*_*bin 5

您可以声明您的共享上下文

RSpec.shared_context "shared stuff" do
  let!(:country) do
    create :country, slug: "kw"
  end unless Country.find_by(slug: "kw").present?
end
Run Code Online (Sandbox Code Playgroud)

并将其包含在配置中

RSpec.configure do |config|
  config.include_context "shared stuff"
end
Run Code Online (Sandbox Code Playgroud)