1 min read

Integrare la libreria di testing RSpec con le notifiche di sistema

Testare il codice è importante e il post di oggi lo vuole far rendere anche più divertente, permettendo di integrare il framework di test con il sistema operativo.

(Gedit con le notifiche)

Ingredienti

  • un framework di testing: RSpec (esempi) è quello che ha la sintassi più piacevole
  • una libreria che gestisca gli eventi del sistema operativo: Watchr un'alternativa ad autotest (che utilizza Cool.io (ex rev))
  • un sistema di notifica non invasivo: libnotify-bin (le notifiche di Ubuntu da CLI)

Workflow

Si hanno i file con i sorgenti (.rb) e i file con le specifiche (*_spec.rb), ogni volta che si salva un file viene eseguita la specifica e il suo output con l'esito dei test viene mostrato per 5s come notifica.

Configurazione

Si definisce un file spec-watchr.rb con le caratteristiche del progetto dove vengono specificati i path dei file da monitorare e i comandi che implementano le azioni.

# file: spec-watchr.rb
# sudo apt-get install libnotify-bin
# sudo gem install cool.io
#
# Run me with:
#
# $ watchr spec-watchr.rb
# --------------------------------------------------
# Convenience Methods
# --------------------------------------------------
def all_spec_files
Dir['spec/**/*_spec.rb']
end
def run_spec_matching(thing_to_match)
matches = all_spec_files.grep(/#{thing_to_match}/i)
if matches.empty?
puts "Sorry, thanks for playing, but there were no matches for #{thing_to_match}"
else
run matches.join(' ')
end
end
def run(files_to_run)
puts("Running: #{files_to_run}")
system('clear; notify-send "RSpec" "`rspec -cfs '+ files_to_run +'`"')
no_int_for_you
end
def run_all_specs
run(all_spec_files.join(' '))
end
# --------------------------------------------------
# Watchr Rules
# --------------------------------------------------
watch('^(.*)\.rb') { |m| run_spec_matching(m[1]) }
watch('^spec/(.*)_spec\.rb') { |m| run_spec_matching(m[1]) }
# --------------------------------------------------
# Signal Handling
# --------------------------------------------------
def no_int_for_you
@sent_an_int = nil
end
Signal.trap 'INT' do
if @sent_an_int then
puts " A second INT? Ok, I get the message. Shutting down now."
exit
else
puts " Did you just send me an INT? Ugh. I'll quit for real if you do it again."
@sent_an_int = true
Kernel.sleep 1.5
run_all_specs
end
end

Si esegue:

watchr spec-watchr.rb

Premendo CTRL+C 2 volte si esce dal monitoraggio, mentre premendo lo una sola volta si forza l' esecuzione di tutte le specifiche contenute nella cartella spec/ .