I got stuck for a few minutes trying to figure out how to write a unit test to check if a value was being set in the flash using flash.now. In Rails’ Test::Unit you can’t just do something like assert_not_nil flash[:notice] because the flash value is discarded at the end of the request, and so the flash is always nil.
The solution is to use Mocha to mock an instance of ActionController::Flash::FlashHash and capture the value being set. Here was my solution:
def test_create_with_empty_email_sets_error_in_flash
hash = {}
ActionController::Flash::FlashHash.any_instance.expects(:now).returns(
hash
)
post :create
assert_not_nil hash[:error]
end