Skip to content

Instantly share code, notes, and snippets.

@ream88
Created July 21, 2012 10:16
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ream88/3155365 to your computer and use it in GitHub Desktop.
Save ream88/3155365 to your computer and use it in GitHub Desktop.
minitest-matchers for controller/functional specs
# Simple minitest matchers which will make your controller/functional specs less pain in the ass.
#
# ==== Dependencies
#
# gem 'minitest'
# gem 'minitest-matchers'
#
# ==== Matchers
#
# +must_have_status+ and its opposite +wont_have_status+ take both one argument which must be one of the following:
# * <tt>:success</tt>
# * <tt>:missing</tt>
# * <tt>:redirect</tt>
# * <tt>:error</tt>
#
# See https://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/testing/assertions/response.rb#L6
# for more info.
#
# And if you are as lazy as I am you will definitely prefer their shortcuts:
#
# * +must_succeed+ is the same as +must_have_status(:success)+
# * +must_miss+ is the same as +must_have_status(:missing)+
# * +must_redirect+ is the same as +must_have_status(:redirect)+
# * +must_fail+ is the same as +must_have_status(:error)+
#
# And of course the shortcuts of their opposites too:
# +wont_succeed+, +wont_miss+, +wont_redirect+, +wont_fail+
#
module ResponseMatchers
module HaveStatus
TYPES = {
success: :succeed,
missing: :miss,
redirect: :redirect,
error: :fail
}
class Matcher
attr_accessor :status
def initialize(status)
self.status = status
end
def matches?(response)
response.send("#{status}?")
end
def failure_message
"Expected response to #{HaveStatus::TYPES[status]}"
end
def negative_failure_message
"Expected response not to #{HaveStatus::TYPES[status]}"
end
end
def have_status(status)
Matcher.new(status)
end
MiniTest::Unit::TestCase.register_matcher(:have_status, :have_status)
TYPES.each do |status, method|
define_method(method) do
have_status(status)
end
MiniTest::Unit::TestCase.register_matcher(method, method)
end
end
end
class MiniTest::Spec
include ::ResponseMatchers::HaveStatus
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment