简体   繁体   English

如何在rspec中的测试运行中共享代码?

[英]How do I share code across a test run in rspec?

I'm writing tests for my API. 我正在为我的API编写测试。 I would like to output the request, params and other such data to a file when the the tests are run. 我想在运行测试时将请求,参数和其他此类数据输出到文件中。 I have added a log call in each of my test methods that calls to my utilites.rb file in spec/support. 我在每个测试方法中添加了一个日志调用,调用spec / support中的utilites.rb文件。 This works as expected except the utilities are loaded on each individual test so I can't write to the file how I want to. 这可以正常工作,除了在每个单独的测试上加载实用程序,所以我不能写我想要的文件。

Here is my spec_helper.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 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

As you can see from the files I would like to append to a test_output.txt after running each test but I would like that file to be cleared between running rspec spec/ each time. 正如您在运行每个测试后我想要附加到test_output.txt的文件中所看到的那样,但我希望在每次运行rspec spec/之间清除该文件。 How can I make this work the way I want it to? 我怎样才能按照我想要的方式完成这项工作?

first of all, i don't think that this is a good idea. 首先,我认为这不是一个好主意。 if you want to debug your application, you can read more about it here: http://nofail.de/2013/10/debugging-rails-applications-in-development/ 如果你想调试你的应用程序,你可以在这里阅读更多相关信息: http//nofail.de/2013/10/debugging-rails-applications-in-development/

if you really really really have to do it, do it like this: 如果你真的真的必须这样做,那就这样做:

assuming you are doing this in your controller tests, add something like this to your spec_helper.rb : 假设您在控制器测试中执行此操作,请在spec_helper.rb添加以下spec_helper.rb

  config.before(:all, type: :controller) do
    clear_log_file
  end

  config.after(:each, type: :controller) do
    log_request
  end

where clear_log_file and log_request refer to the code you will use according to your Utilities module. 其中clear_log_filelog_request指的是您将根据Utilities模块使用的代码。

this way you won't even have to add anything to your specs to write the log. 通过这种方式,您甚至不必在规范中添加任何内容来编写日志。

i'm just about 90% sure that this works, but at least it's the general direction of what you should do. 我只有90%肯定这是有效的,但至少它是你应该做的一般方向。

I had to add to the spec helper. 我不得不添加到规范助手。

config.before(:suite) do
  #code I added
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM