Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
partial viewでインスタンス変数を使っていないことをテスト(slim版)
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