我正在为我的API编写测试。我希望在运行测试时将请求、参数和其他此类数据输出到一个文件。我在每个调用实用程序的测试方法中添加了一个日志调用。spec/support中的Rb文件。这可以像预期的那样工作,除了在每个单独的测试上加载实用程序,所以我不能按我想要的方式写入文件。
这是我的spec_helper.rb
# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../conf
require 'rspec/autorun'ig/environment", __FILE__)
require 'rspec/rails'
# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }
RSpec.configure do |config|
# ## Mock Framework
#
# If you prefer to use mocha, flexmock or RR, uncomment the appropriate line:
#
# config.mock_with :mocha
# config.mock_with :flexmock
# config.mock_with :rr
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
config.fixture_path = "#{::Rails.root}/spec/fixtures"
# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
config.use_transactional_fixtures = true
# If true, the base class of anonymous controllers will be inferred
# automatically. This will be the default behavior in future versions of
# rspec-rails.
config.infer_base_class_for_anonymous_controllers = false
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = "random"
config.include Requests::JsonHelpers, type: :request
config.include Utilities
end
Utilities.rb
module Utilities
EQUAL_STRING = "=========================n"
TEST_OUTPUT = "test_output.txt"
def log
s = "#{request.method} #{request.path}n" +
"Controller: #{request.params[:controller]}n" +
"Action: #{request.params[:action]}n" +
"Params:n" +
JSON.pretty_generate(JSON.parse(request.query_parameters.to_json)) + "n" +
"n" +
"Response:n" +
"Status: #{response.status}n" +
JSON.pretty_generate(JSON.parse(response.body)) + "n" +
EQUAL_STRING
write_to_file s
end
private
def write_to_file(input)
if @file.nil?
@file = TEST_OUTPUT
if File.exists? @file
File.delete @file
end
end
File.open(@file, 'a') do |f|
puts input
f.puts input
end
end
end
正如您从文件中看到的,我希望在运行每个测试后附加到test_output.txt,但我希望该文件在每次运行rspec spec/
之间被清除。我怎样才能让这件事按我想要的方式进行?
首先,我不认为这是个好主意。如果您想调试您的应用程序,您可以在这里阅读更多信息:http://nofail.de/2013/10/debugging-rails-applications-in-development/
如果你真的真的真的必须这样做,就像这样做:
假设您在控制器测试中这样做,请在spec_helper.rb
中添加如下内容:
config.before(:all, type: :controller) do
clear_log_file
end
config.after(:each, type: :controller) do
log_request
end
其中clear_log_file
和log_request
是指您将根据Utilities
模块使用的代码。
这样,您甚至不需要在spec中添加任何内容来编写日志。
我只有90%的把握,但至少这是你应该做的大方向。
我必须添加到规范帮助器。
config.before(:suite) do
#code I added
end