【问题标题】:How to write unit test cases for rake tasks in rails?如何为 Rails 中的 rake 任务编写单元测试用例?
【发布时间】:2012-03-08 14:18:03
【问题描述】:

大家好,我有这种情况,我需要在我的 rails 应用程序中为 rake 任务编写单元测试用例,但我想不出办法。有人试过吗?

【问题讨论】:

    标签: ruby-on-rails unit-testing testing rake


    【解决方案1】:

    你能做的就是这个..

    1. 编写将在模型或类中的 rake 任务上运行的逻辑。

    2. 为该模型编写单元测试。

    3. 最后在 rake 任务中调用该方法。

    【讨论】:

    【解决方案2】:

    我发现this 链接用于使用 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
    

    【讨论】:

    • 请在此链接周围添加一些上下文。它可能会变为无效,留下一个破碎的答案。
    猜你喜欢
    • 2018-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-04
    • 2019-02-22
    • 1970-01-01
    相关资源
    最近更新 更多