Method expectations in MiniTest

只谈情不闲聊 提交于 2019-12-23 17:45:08

问题


I'm trying to write a test for ActiveRecord - and Rails uses MiniTest for its tests, so I don't have a choice of test framework. The condition I want to test is this (from the db:create rake tasks, pulled into a method for the purpose of this example):

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

So, I want to test that $stderr receives puts if the File exists, but otherwise does not. In RSpec, I would have done this:

File.stub :exist? => true

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

create_db

What's the equivalent in MiniTest? assert_send doesn't seem to behave as I expect (and there's not really any documentation out there - should it go before the execution, like should_receive, or after?). I was thinking I could temporarily set $stderr with a mock for the duration of the test, but $stderr only accepts objects that respond to write. You can't stub methods on mocks, and I don't want to set an expectation of the write method on my stderr mock - that'd mean I'm testing an object I'm mocking.

I feel like I'm not using MiniTest the right way here, so some guidance would be appreciated.

An update: here is a solution that works, but it is setting the expectation for :write, which is Not Right.

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

回答1:


So, it turns out Rails uses Mocha in combination with Minitest, which means we can take advantage of Mocha's far nicer message expectations. A working test looks like this:

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


来源:https://stackoverflow.com/questions/11067573/method-expectations-in-minitest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!