Created
July 21, 2012 10:16
-
-
Save ream88/3155365 to your computer and use it in GitHub Desktop.
minitest-matchers for controller/functional specs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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