Skip to content

Instantly share code, notes, and snippets.

@vsevolod
Last active August 21, 2020 16:22
Show Gist options
  • Save vsevolod/1addd9d7ea8978ec0e14bd8771ce5b93 to your computer and use it in GitHub Desktop.
Save vsevolod/1addd9d7ea8978ec0e14bd8771ce5b93 to your computer and use it in GitHub Desktop.
Best success version spec files with build_stubbed instead of create
require_relative 'spec/spec_helper.rb'
require 'pry-byebug'
class SpecFile
CREATE = ' create(:'.freeze
BUILD_STUBBED = ' build_stubbed(:'.freeze
attr_reader :file_name, :content_array
def initialize(file_name)
@file_name = file_name
content = File.open(file_name, 'r:UTF-8').read
@content_array = content.split(CREATE)
@cached_statuses = {}
end
def write_best
return if content_array.size == 1
puts("Started #{file_name}")
positions = Array.new(content_array.size - 1) { false }
positions.size.times do
before = positions.count(&:itself)
switch(positions)
break if before == positions.count(&:itself)
end
puts("Completed with result #{positions.inspect}")
write_position(positions)
end
private
def switch(positions)
positions.each.with_index do |position, i|
next if position
positions[i] = true
write_position(positions)
line = 1 + content_array[0..i].sum { |x| x.scan("\n").size }
status = get_from_cache(positions, line) || run(positions, line)
positions[i] = false if status != 0
end
end
def write_position(positions)
result = content_array[0].dup
positions.each.with_index do |val, index|
result << (val ? BUILD_STUBBED : CREATE)
result << content_array[index+1]
end
File.open(file_name, 'w+') { |f| f.write(result) }
positions.count(&:itself)
end
def get_from_cache(positions, line)
name = positions.join + "#{line}"
@cached_statuses[name]
end
def puts_to_cache(positions, line, result)
name = positions.join + "#{line}"
@cached_statuses[name] = result
end
def run(positions, line)
pattern = "#{file_name}:#{line}"
pid = fork {
code = RSpec::Core::Runner.run([pattern])
raise 'With errors' if code != 0
}
_, status = Process.waitpid2(pid)
result = status.exitstatus
puts "#{pattern} #{positions.inspect} => #{result}"
puts_to_cache(positions, line, result)
result
end
end
Dir["spec/**/*_spec.rb"].each do |file|
SpecFile.new(file).write_best
end
@vsevolod
Copy link
Author

Sample output:

Started spec/decorators/table/menu_item_decorator_spec.rb
bundle exec rspec spec/decorators/table/menu_item_decorator_spec.rb:10 [true, false, false, false] => 0
bundle exec rspec spec/decorators/table/menu_item_decorator_spec.rb:10:15 [true, true, false, false] => 0
bundle exec rspec spec/decorators/table/menu_item_decorator_spec.rb:10:15:20 [true, true, true, false] => 0
bundle exec rspec spec/decorators/table/menu_item_decorator_spec.rb:10:15:20:40 [true, true, true, true] => 0
Completed with result [true, true, true, true]

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