Class: MKBrut::Segments::BareBones::InsertEndToEndTestCode

Inherits:
Ops::PrismParsingOp show all
Defined in:
lib/mkbrut/segments/bare_bones.rb

Instance Method Summary collapse

Methods inherited from Ops::BaseOp

dry_run=, dry_run?, #dry_run?, fileutils_args, #fileutils_args

Constructor Details

#initialize(file:, code:) ⇒ InsertEndToEndTestCode

Returns a new instance of InsertEndToEndTestCode.



129
130
131
132
# File 'lib/mkbrut/segments/bare_bones.rb', line 129

def initialize(file:, code:)
  @file = file
  @code = code
end

Instance Method Details

#callObject



133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
# File 'lib/mkbrut/segments/bare_bones.rb', line 133

def call
  if dry_run?
    puts "Would insert end-to-end test code into #{@file}:\n\n#{@code}\n"
    return
  end
  parse_file!

  found_describe = false
  first_it_block = nil

  @tree.value.statements.body.each do |top|
    if top.is_a?(Prism::CallNode) &&
       top.name == :describe      &&
       top.block
      found_describe = true

      statements = top.block.body
      if statements.respond_to?(:body)
        statements.body.each do |statement|
          if statement.is_a?(Prism::CallNode) &&
             statement.name == :it            &&
             statement.block

            first_it_block = statement
            break

          end
        end
      end
    end
  end
  if !first_it_block
    if found_describe
    raise "Could not find an 'it' block inside the first 'describe' in '#{@file}'"
    else
    raise "Could not find a 'describe' block in '#{@file}'"
    end
  end

  insertion_point = first_it_block.block.location.end_offset - 3

  block_line = @source.lines[first_it_block.location.start_line - 1]
  describe_indent = block_line[/^\s*/] 
  it_indent = describe_indent + "  "

  new_source = @source.dup.insert(insertion_point, "\n#{it_indent}#{@code}\n#{describe_indent}")
  File.open(@file, "w") do |file|
    file.puts new_source
  end
end