为rake任务编写单元测试

时间:2018-05-07 16:45:08

标签: ruby-on-rails ruby rake rake-task rakefile

我有一个简单的rails应用程序,我将数据从csv导入我的rails应用程序,该应用程序运行正常,但我不知道从哪里开始测试此rake任务,以及模块化rails应用程序中的位置。任何帮助,将不胜感激。谢谢!

csv_importer.task

require 'csv_importer/engine'

task users: :environment do
  desc 'Import users from csv'

  WebImport.new(url: 'http://blablabla/people.csv').call
end

csv_importer.rb

require 'csv_importer/engine'

class WebImport
  def initialize(url)
    @url = url
  end

  def call
    url = 'http://blablabla/people.csv'
    # I forced encoding so avoid UndefinedConversionError "\xC3" from ASCII-8BIT to UTF-8
    csv_string = open(url).read.force_encoding('UTF-8')
    counter = 0
    duplicate_counter = 0

    user = []
    CSV.parse(csv_string, headers: true, header_converters: :symbol) do |row|
      next unless row[:name].present? && row[:email_address].present?
      user = CsvImporter::User.create row.to_h
      if user.persisted?
        counter += 1
      else
        duplicate_counter += 1
      end
    end
    p "Email duplicate record: #{user.email_address} - #{user.errors.full_messages.join(',')}" if user.errors.any?

    p "Imported #{counter} users, #{duplicate_counter} duplicate rows ain't added in total"
  end
end

我做了什么:

csv_importer_test.rb

require 'test_helper'
require 'rake'

class CsvImporter::Test < ActiveSupport::TestCase
  test 'truth' do
    assert_kind_of Module, CsvImporter
  end

  test 'override_application' do
    @rake = Rake::Application.new
    Rake.application = @rake
    assert_equal @rake, Rake.application
  end

  test '' do
    # something here
  end
end

这样可以正常工作并填充我的数据库。如何编写TestCase来捕获此解决方案?

1 个答案:

答案 0 :(得分:2)

您实际上已经做了好事,将所有任务逻辑保存在rake之外的库文件中。我在这里再往前走......

require 'csv_importer/engine'

class WebImport
  def initialize(url)
    @url = url
  end

  def call
    url = 'http://blablabla/people.csv'
    csv_string = open(url).read.force_encoding('UTF-8')

    string_to_users(csv_string)
 end

 def string_to_users(csv_string)
    counter = 0
    duplicate_counter = 0
    ....
 end
end

在这里看到我们已经删除了我们如何调用我们的方法(我们不关心它是否是Rake或Ruby调用我们的方法)并且可能分离我们获取数据的方式。

接下来,我会按以下方式编写测试:

test 'override_application' do
  a = WebImport.new(url: 'http://blablabla/people.csv')

  a.string_to_users("a,b,c,d,e")  # <-- a string you saved from some manual run, or that contains maybe a sample record with their exact format
  assert_equal Users.count, 42
end

鉴于你现在已经分开了:

  • 您如何调用代码,因为它在单独的库/模块中远离Rake
  • 您的代码如何获取数据(通常由call提供数据...但您可以在此处插入数据)

那么你应该准备好接受你的测试驱动设计了!