Last active
August 29, 2015 14:12
-
-
Save CoryFoy/2db13b5b233e4968721d to your computer and use it in GitHub Desktop.
Base test for ensuring all controller actions that take an ID will throw a RecordNotFound for invalid IDs
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
class BaseTest < ActionDispatch::IntegrationTest | |
test "all controllers should raise exceptions with invalid IDs" do | |
routes = Rails.application.routes.routes | |
id_based_routes = routes.find_all { |r| r.required_parts.include?(:id) } | |
id_based_routes.each do |route| | |
klass = "#{route.defaults[:controller]}_controller".classify.constantize | |
@controller = klass.new | |
num_required_parts = route.required_parts.length | |
name = route.name | |
nonexistent_id = -1 | |
if name.present? | |
route_path = Rails.application.routes.url_helpers.send("#{name}_path", num_required_parts.times.map { nonexistent_id }) | |
else | |
route_path = "/#{route.defaults[:controller]}/#{nonexistent_id}" | |
end | |
request_method = route.constraints[:request_method].to_s[8..-3].downcase | |
begin | |
r = send(request_method.to_sym, route_path) | |
flunk("No exception raised with an invalid ID for #{route.inspect}") | |
rescue Exception => ex | |
assert_equal ActiveRecord::RecordNotFound, ex.class | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This came out of a discussion about testing controller actions that just do a find. I was curious if I could write a single global test that would ensure all controllers which take an ID would throw a RecordNotFound if an invalid ID was passed in. This hackish thing seems to do that. I don't know if I would actually use it, yet, but it was a fun exercise in route mapping.