gpt4 book ai didi

ruby - 为 RSpec 套件中的所有示例设置一次变量(不使用全局变量)

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

在 RSpec 套件中设置一个变量一次供所有示例使用的常规方法是什么?

我目前在 spec_helper 中设置了一个全局变量,用于检查规范是否在“ Debug模式”下运行

$debug = ENV.key?('DEBUG') && (ENV['DEBUG'].casecmp('false') != 0) && (ENV['DEBUG'].casecmp('no') != 0)

如何在不使用全局变量且不重新计算每个上下文和/或示例的值的情况下,将此信息提供给套件中的所有示例? (我的理解是,使用 before(:all) block 会根据上下文重新计算一次;但是,before(:suite) 不能用于设置实例变量。)

(注意:我要求更多了解解决此特定问题的良好设计。我知道一个全局的没什么大不了的。)

最佳答案

为此,我通常会编写可以包含在 spec_helper.rb 文件中的自定义模块。

假设我正在测试后端 API,我不想每次都解析 JSON 响应正文。

spec/
spec/spec_helper.rb
spec/support/request_helper.rb
spec/controllers/api/v1/users_controller_spec.rb

我首先在 support 子文件夹下的模块中定义一个函数。

# request_helper.rb
module Request
module JsonHelpers
def json_response
@json_response ||= JSON.parse(response.body, symbolize_names: true)
end
end
end

然后我默认为某些测试类型包含这个模块

#spec_helper.rb
#...
RSpec.configure do |config|
config.include Request::JsonHelpers, type: :controller
end

然后我使用测试中定义的方法。

# users_controller_spec.rb
require 'rails_helper'

RSpec.describe Api::V1::UsersController, type: :controller do
# ...

describe "POST #create" do

context "when is successfully created" do
before(:each) do
@user_attributes = FactoryGirl.attributes_for :user
post :create, params: { user: @user_attributes }
end

it "renders the json representation for the user record just created" do
user_response = json_response[:user]
expect(user_response[:email]).to eq(@user_attributes[:email])
end

it { should respond_with 201 }
end
end

在您的情况下,您可以创建一个模块,例如

module EnvHelper
def is_debug_mode?
@debug_mode ||= ENV['DEBUG']
end
end

然后您可以包含它并在您的测试中简单地使用方法 is_debug_mode?

关于ruby - 为 RSpec 套件中的所有示例设置一次变量(不使用全局变量),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46200096/

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