-->

方法期望在MINITEST(Method expectations in MiniTest)

2019-09-18 05:04发布

我试图写一个测试ActiveRecord的 - 和Rails使用MINITEST它的测试,所以我没有测试框架的选择。 我想测试的条件是这个(从DB:创建耙任务,被拉入这个例子的目的的一种方法):

def create_db
  if File.exist?(config['database'])
    $stderr.puts "#{config['database']} already exists"
  end
end

所以,我想测试,如果文件存在$标准错误收放,但在其他方面却没有。 在RSpec的,我会做这样的:

File.stub :exist? => true

$stderr.should_receive(:puts).with("my-db already exists")

create_db

是什么在MINITEST等价? assert_send似乎并没有表现得如我所料(真的有没有任何文件在那里 - 在执行前应该去,像should_receive或之后?)。 我想我可以临时设置$标准错误与测试的持续时间的模拟,但$标准错误只接受响应写对象。 你不能存根上嘲弄的方法,我不想设定写入方法的期望在我的标准错误模拟 - 那简直是说我测试的对象,我嘲笑。

我觉得我不使用MINITEST这里以正确的方式,让一些指导,将不胜感激。

更新:这里是一个可行的解决方案,但它设置为期望:写的,这是不对的。

def test_db_create_when_file_exists
  error_io = MiniTest::Mock.new
  error_io.expect(:write, true)
  error_io.expect(:puts, nil, ["#{@database} already exists"])
  File.stubs(:exist?).returns(true)

  original_error_io, $stderr = $stderr, error_io

  ActiveRecord::Tasks::DatabaseTasks.create @configuration

ensure
  $stderr = original_error_io unless original_error_io.nil?
end

Answer 1:

因此,事实证明Rails使用摩卡结合MINITEST,这意味着我们可以采取的摩卡的远更好消息的预期的优势。 一个工作测试看起来是这样的:

def test_db_create_when_file_exists
  File.stubs(:exist?).returns(true)

  $stderr.expects(:puts).with("#{@database} already exists")

  ActiveRecord::Tasks::DatabaseTasks.create @configuration
end


文章来源: Method expectations in MiniTest