ruby - 特征测试 rake 任务将输出添加到标准输出。如何避免这种情况?

标签 ruby rspec rake stdout

我尝试对 Rake 任务进行功能测试并捕获其输出:

这是一个完整的集成测试(功能测试),它 意味着我想端到端地测试它。所以我对 stub 不感兴趣 出一些 ConsoleRenderer 类,只是测试当我运行任务时,我 在 stdout 中查看特定输出。

实现,大大简化了

namespace :output do
  task :world do
    print 'hello world'
  end

  task :mars do
    print 'hello mars'
  end
end

以及功能测试(rspec 3.3):

require 'feature_helper'

describe 'some output' do
  before do
    Rails.application.load_tasks
  end

  after do
    Rake::Task['output:world'].reenable
    Rake::Task['output:mars'].reenable
  end

  it 'outputs' do
    expect { Rake::Task['output:world'].invoke }.to output('hello world').to_stdout
  end

  it 'outputs again' do
    expect { Rake::Task['output:world'].invoke }.to output('hello world').to_stdout
  end

  it 'outputs mars' do
    expect { Rake::Task['output:mars'].invoke }.to output('hello mars').to_stdout
  end
end

运行时,过去运行的输出以某种方式加起来:

$ bundle exec rspec spec/features/output_spec.rb --order defined
.FF

Failures:

  1) some output outputs again
     Failure/Error: expect { Rake::Task['output:world'].invoke }.to output('hello world').to_stdout
       expected block to output "hello world" to stdout, but output "hello worldhello world"
     # ./spec/features/output_spec.rb:18:in `block (2 levels) in <top (required)>'

  2) some output outputs mars
     Failure/Error: expect { Rake::Task['output:mars'].invoke }.to output('hello mars').to_stdout
       expected block to output "hello mars" to stdout, but output "hello marshello marshello mars"
     # ./spec/features/output_spec.rb:22:in `block (2 levels) in <top (required)>'

为了说明,我按照定义的顺序运行测试。 第一个测试通过。第二个失败了,因为它以某种方式包含了 之前测试中 $stdout 的输出,或者自己运行两次。第三个也是如此(它似乎自己运行了三次)。

我怀疑这是 Rake 任务中的一些东西,因为当我简化 测试只是 print 一些东西,这个添加不会发生:

it 'outputs' do
  expect { print 'hello world' }.to output('hello world').to_stdout
end

it 'outputs again' do
  expect { print 'hello world' }.to output('hello world').to_stdout
end

it 'outputs mars' do
  expect { print 'hello mars' }.to output('hello mars').to_stdout
end

这一切顺利。

请注意,在控制台上运行

Rake::Task['output:mars'].invoke
Rake::Task['output:mars'].reenable
Rake::Task['output:mars'].invoke

输出一次“hello mars”,然后再次输出“hello mars”。问题不 在这样的环境中 self 繁殖。

我需要什么来重置、重新启用、重新导入、截断或其他 更改,以便输出不相加?

最佳答案

原来 reenable 不是正确的调用。相反,我应该使用 clear .它自己的文档是“通常在单元测试中使用”。

after do
  Rake.application.clear
end

注意:这修复了它,但我仍然不知道问题中描述的设置为何或如何在某个时候运行任务三次。因此,解释为什么行为是这样的答案以及为什么运行clear没有那个,将比我自己的答案更受欢迎。

关于ruby - 特征测试 rake 任务将输出添加到标准输出。如何避免这种情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32314830/

相关文章:

ruby-on-rails - 我怎样才能使这个方法更简洁?

ruby-on-rails - Rails 3 + CarrierWave + Rspec : model validation

Ruby rake 任务线程优化

ruby - 如何让 Rake 任务在所有其他任务之后运行? (即 Rake AfterBuild 任务)

ruby - 什么是基于文件的源代码?

Ruby Signal Trapper 优先级

ruby - 如何测试是否正在使用某些特定的 Rack 中间件?

mysql错误: can't destroy an object that is created using factoryGirl

ruby - 加载错误 : cannot load such file -- rspec/core/rake_task

ruby - 在 Ruby Rails 安装上找不到 rake