Skip to content

Instantly share code, notes, and snippets.

@CoryFoy
Last active August 29, 2015 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CoryFoy/2db13b5b233e4968721d to your computer and use it in GitHub Desktop.
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
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
@CoryFoy
Copy link
Author

CoryFoy commented Jan 6, 2015

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment