簡體   English   中英

如何為Rails中的rake任務編寫單元測試用例?

[英]How to write unit test cases for rake tasks in rails?

大家好,我有這種情況,我需要在Rails應用程序中為rake任務編寫單元測試用例,但我找不到解決方法。 有人嘗試過嗎?

你可以做的是這個..

  1. 編寫將在模型或類內的rake任務上運行的邏輯。

  2. 為該模型編寫單元測試。

  3. 最后,在您的rake任務中調用該方法。

我發現這個鏈接,使用rspec的編寫測試用例。 簡短的測試用例

基本上,創建一個模塊,該模塊將解析rake任務的名稱,並使我們可以使用關鍵字task,在該模塊上我們可以將其稱為expect { task.execute }.to output("your text\\n").to_stdout

這是創建文件的方法,

module TaskExampleGroup extend ActiveSupport::Concern

    included do
    let(:task_name) { self.class.top_level_description.sub(/\Arake /, "") }
    let(:tasks) { Rake::Task }

    # Make the Rake task available as `task` in your examples:
    subject(:task) { tasks[task_name] }
    end
end

將其添加到rspec初始化程序文件中

RSpec.configure do |config|

    # Tag Rake specs with `:task` metadata or put them in the spec/tasks dir
    config.define_derived_metadata(:file_path => %r{/spec/tasks/}) do |metadata|
    metadata[:type] = :task
    end

    config.include TaskExampleGroup, type: :task

    config.before(:suite) do
    Rails.application.load_tasks
    end
end

暫無
暫無

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

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