Created
May 23, 2021 13:46
-
-
Save alpaca-tc/c19f00d583234a2c73eda6d8378b8c50 to your computer and use it in GitHub Desktop.
partial viewでインスタンス変数を使っていないことをテスト(slim版)
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
require 'parser/current' | |
RSpec.describe 'View spec' do | |
describe 'partial view' do | |
# partial viewの一覧 | |
let(:partial_views) do | |
path = Rails.application.paths['app/views'].first | |
Dir.glob("#{path}/**/_*.html.slim") | |
end | |
# slimをRubyのコードに変換する | |
def parse_slim(content) | |
Slim::Engine.new.call(content) | |
end | |
# インスタンス変数へのアクセスのみを取り出す | |
def collect_instance_variable_nodes(node, collector = []) | |
if node.type == :ivar | |
collector.push(node) | |
end | |
node.children.each do |descendant| | |
collect_instance_variable_nodes(descendant, collector) if descendant.is_a?(Parser::AST::Node) | |
end | |
collector | |
end | |
# partial viewでは、インスタンス変数を使ってはいけない | |
it "doesn't use instance variables" do | |
partial_views.each do |partial_view| | |
content = File.read(partial_view) | |
ruby_code = parse_slim(content) | |
node = Parser::CurrentRuby.parse(ruby_code) | |
nodes = collect_instance_variable_nodes(node) | |
expect(nodes).to be_empty, -> { | |
relative_path = Pathname.new(partial_view).relative_path_from(Rails.root).to_s | |
instance_variable_names = nodes.map { |instance_variable_node| instance_variable_node.children.last } | |
<<~MESSAGE | |
Do not use instance variable from partial view. #{relative_path} | |
#{instance_variable_names} | |
MESSAGE | |
} | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment