簡體   English   中英

編寫rake任務的單元測試

[英]writing unit test for a rake task

我有一個簡單的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來捕獲此解決方案?

實際上,您已經做好了將所有任務邏輯保存在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提供的數據...,但是您可以在此處插入數據本身)

然后,您就應該准備好進行測試驅動的設計了!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM