Skip to content

Instantly share code, notes, and snippets.

@madogiwa0124
Last active September 1, 2019 10:45
Show Gist options
  • Save madogiwa0124/18a51a8d2e529836084c13d7e12e69ea to your computer and use it in GitHub Desktop.
Save madogiwa0124/18a51a8d2e529836084c13d7e12e69ea to your computer and use it in GitHub Desktop.
auto route request spec.
module RoutingTestHelper
def routes(namespace: nil, actions: nil, ignore_paths: [])
filtered_routes = all_routes
filtered_routes.select! { |route| route.name.include?(namespace) } if namespace
filtered_routes.select! { |route| actions.include?(route.action) } if actions
filtered_routes.select! { |route| ignore_paths.exclude?(route.name) } if ignore_paths
filtered_routes.reject { |route| route.url.nil? }
end
private
def rails_routes
Rails.application.routes
end
def all_routes
rails_routes.routes.select(&:name).map do |route|
Route.new(route, rails_routes.url_helpers)
end
end
class Route
def initialize(route, url_helpers)
@name = route.name
@action = route.requirements[:action]
@controller = route.defaults[:controller]
@keys = route.path.required_names
@url_helpers = url_helpers
end
attr_reader :name, :action, :controller, :keys, :url_helpers
def attributes
attributes = { host: Capybara.server_host, controller: controller, action: action }
# NOTE: must be created record with key before execution.
attributes.tap { keys.each { |key| attributes.merge!(key.to_sym => 1) } }
end
def url
url_helpers.url_for attributes
rescue ActionController::UrlGenerationError
nil
end
end
end
require 'rails_helper'
include RoutingTestHelper
RSpec.describe '画面に正常に遷移できるか確認', type: :request do
let!(:user) { FactoryBot.create(:user, :admin) }
before { allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(user) }
IGNORE_PATHS = %w[root new_user_session login].freeze
routes(actions: ['new', 'index'], ignore_paths: IGNORE_PATHS).each do |route|
it "#{route.name}(#{route.url})" do
get route.url
expect(response.status).to eq 200
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment