问题
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