为此,我通常编写自定义模块,将其包含在spec_helper.rb
file.
假设我正在测试后端 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?
在你的测试中。