Search code examples
ruby-on-railsrspecguard

How can I play sound on rspec success/failure when using guard


I had it configured once with autotest, but lately I'm using guard-rspec to run my specs in the background. I do have growl notifications but this requires reading the actual notification text which is a distraction during a fast red-green cycle. I would prefer a sound notification for success and failure, but I can't find any ready-to-use example of such a setup.


Solution

  • I also haven't seen a such example setup, so you need to implement a Notifier:

    module Guard::Notifier::Sound
      extend self
    
      def available?(silent = false, options = {})
        true
      end
    
      def notify(type, title, message, image, options = { })
        puts 'Play sound: ', type
      end
    end
    

    You can place this code directly into your Guardfile, register and make use of it with the following code:

    Guard::Notifier::NOTIFIERS << [[:sound, ::Guard::Notifier::Sound]]
    notification :sound
    

    Of course you need to implement the actual sound playing. A simple implementation would be to fork to an external player like:

    def notify(type, title, message, image, options = { })
      fork{ exec 'mpg123','-q',"spec/support/sound/#{ type }.mp3" }
    end
    

    Update

    With Spork the above direct inclusion into the Guardfile will not work, because Spork runs in a separate process and will not evaluate it. You need to create a supporting file, e.g. spec/support/sound_notifier.rb with a content like this:

    module Guard::Notifier::Sound
      extend self
    
      def available?(silent = false, options = {})
        true
      end
    
      def notify(type, title, message, image, options = { })
        fork{ exec 'mpg123','-q',"spec/support/sound/#{ type }.mp3" }
      end
    end
    
    Guard::Notifier::NOTIFIERS << [[:sound, ::Guard::Notifier::Sound]]
    

    and having just

    require 'spec/support/sound_notifier'
    notification :sound
    

    in the Guardfile. Next you need to load the sound_notifier also in the Spork process. Since I do not use Spork I cannot verify it, but when I remember correctly happens in the spec_helper.rb:

    Spork.prefork do
      require 'spec/support/sound_notifier'
    end