Guard

Guard is a gem that allows you to observe your project's files for change and perform actions based on that change. The first thing you will need to do is add Guard (and its helpers for Bundler and RSpec) to the end of your Gemfile:

[~/srcLPPclases/question-simple_choice(master)]$ vi Guardfile 

source 'https://rubygems.org'

# Specify your gem's dependencies in question-simple_choice.gemspec

group :development, :test do
  gem 'rspec'
  gem 'pry'
  gem 'guard'
  # do not call require when you start Bundler
  gem 'guard-rspec', require: false
end
You should now run bundle install in your project root to install Guard if it isn't already.
[~/srcLPPclases/question-simple_choice(master)]$ guard --version
Guard version 2.8.0

[~/srcLPPclases/question-simple_choice(master)]$ guard help
Commands:
  guard help [COMMAND]  # Describe available commands or one specific command
  guard init [GUARDS]   # Generates a Guardfile at the current directory (if it i...
  guard list            # Lists Guard plugins that can be used with init
  guard notifiers       # Lists notifiers and its options
  guard show            # Show all defined Guard plugins and their options
  guard start           # Starts Guard
  guard version         # Show the Guard version

Now we need to initialize Guard and configure it for our project. Luckily, Guard comes with its own command line helpers:

[~/srcLPPclases/question-simple_choice(master)]$ guard help init
Usage:
  guard init [GUARDS]

Options:
  -b, [--bare=Generate a bare Guardfile without 
          adding any installed plugin into it], [--no-bare]  

Generates a Guardfile at the current directory (if it is not already
there) and adds all installed Guard plugins or the given GUARDS into it

Si solo queremos generar código para vigilar el Gemfile usando guard-bundler:

[~/srcLPPclases/question-simple_choice(master)]$ guard init rspec
16:18:14 - INFO - Writing new Guardfile to 
   /Users/casiano/local/src/ruby/LPP/clases/question-simple_choice/Guardfile
16:18:14 - INFO - rspec guard added to Guardfile, 
                  feel free to edit it

[~/srcLPPclases/question-simple_choice(master)]$ cat Guardfile 
# A sample Guardfile
# More info at https://github.com/guard/guard#readme

# Note: The cmd option is now required due to the increasing number of ways
#       rspec may be run, below are examples of the most common uses.
#  * bundler: 'bundle exec rspec'
#  * bundler binstubs: 'bin/rspec'
#  * spring: 'bin/rsspec' (This will use spring if running and you have
#                          installed the spring binstubs per the docs)
#  * zeus: 'zeus rspec' (requires the server to be started separetly)
#  * 'just' rspec: 'rspec'
guard :rspec, cmd: 'bundle exec rspec' do
  watch(%r{^spec/.+_spec\.rb$})
  watch(%r{^lib/(.+)\.rb$})     { |m| "spec/lib/#{m[1]}_spec.rb" }
  watch('spec/spec_helper.rb')  { "spec" }

  # Rails example
  watch(%r{^app/(.+)\.rb$})                           { |m| "spec/#{m[1]}_spec.rb" }
  watch(%r{^app/(.*)(\.erb|\.haml|\.slim)$})          { |m| "spec/#{m[1]}#{m[2]}_spec.rb" }
  watch(%r{^app/controllers/(.+)_(controller)\.rb$})  { |m| ["spec/routing/#{m[1]}_routing_spec.rb", "spec/#{m[2]}s/#{m[1]}_#{m[2]}_spec.rb", "spec/acceptance/#{m[1]}_spec.rb"] }
  watch(%r{^spec/support/(.+)\.rb$})                  { "spec" }
  watch('config/routes.rb')                           { "spec/routing" }
  watch('app/controllers/application_controller.rb')  { "spec/controllers" }
  watch('spec/rails_helper.rb')                       { "spec" }

  # Capybara features specs
  watch(%r{^app/views/(.+)/.*\.(erb|haml|slim)$})     { |m| "spec/features/#{m[1]}_spec.rb" }

  # Turnip features and steps
  watch(%r{^spec/acceptance/(.+)\.feature$})
  watch(%r{^spec/acceptance/steps/(.+)_steps\.rb$})   { |m| Dir[File.join("**/#{m[1]}.feature")][0] || 'spec/acceptance' }
end
Si solo queremos generar código para vigilar las pruebas usando guard-rspec:
guard init rspec

  1. Guard works similarly to Bundler and Rake by creating a Guardfile in your project's root directory.

  2. These commands automatically add example configuration for each guard type to the Guardfile (after guard init creates the file to begin with).

  3. While I'm going to tell you explicitly what to put in your Guardfile, the init commands can really help jog your memory if you're trying to do it from scratch.

Let's modify our Guardfile to look like this:

guard 'bundler' do
  watch('Gemfile')
end

guard 'rspec', :version => 2 do
  watch(%r{^spec/.+_spec\.rb$})
  watch(%r{^lib/(.+)\.rb$})     { |m| "spec/#{m[1]}_spec.rb" }
  watch('spec/spec_helper.rb')  { "spec" }
end
Guard works by watching certain files in your project and then performing actions when those files change.

  1. The first guard
    guard 'bundler' do
      watch('Gemfile')
    end
    
    tells us to watch for the Gemfile to change, and run bundle install when that happens.

  2. The second guard tells us to watch all of our RSpec test files, our spec_helper, and the corresponding library files for each of our RSpec tests.

  3. This means that when you change a file, Guard can automatically re-run the tests for that specific file only.

  4. Now that your Guardfile is properly configured, you can just run bundle exec guard start from your project's root directory.

    [~/srcLPPruby/building_gems/bleigh_tutorial_to_building_gems/my-gem(master)]$ guard help start
    Usage:
      guard start
    
    Options:
      -c, [--clear=Auto clear shell before each action]                            
      -n, [--notify=Notifications feature]                                         
      -d, [--debug=Show debug information]                                         
      -g, [--group=Run only the passed groups]                                     
      -P, [--plugin=Run only the passed plugins]                                   
      -w, [--watchdir=Specify the directories to watch]                            
      -G, [--guardfile=Specify a Guardfile]                                        
      -i, [--no-interactions=Turn off completely any Guard terminal interactions]  
      -B, [--no-bundler-warning=Turn off warning when Bundler is not present]      
          [--show-deprecations=Turn on deprecation warnings]                       
      -l, [--latency=Overwrite Listen's default latency]                           
      -p, [--force-polling=Force usage of the Listen polling listener]             
    
    Starts Guard
    
  5. When excuting guard, it shows a pry console, with some Guard specific pry commands:
    [~/srcLPPruby/building_gems/bleigh_tutorial_to_building_gems/my-gem(master)]$ guard
    17:41:40 - INFO - Guard here! It looks like your project has a Gemfile, yet you are running
    > [#] `guard` outside of Bundler. If this is your intent, feel free to ignore this
    > [#] message. Otherwise, consider using `bundle exec guard` to ensure your
    > [#] dependencies are loaded correctly.
    > [#] (You can run `guard` with --no-bundler-warning to get rid of this message.)
    17:41:40 - WARN - Guard::RSpec DEPRECATION WARNING: The :version option is deprecated. Only RSpec ~> 2.14 is now supported.
    17:41:40 - INFO - Guard is using TerminalTitle to send notifications.
    17:41:40 - INFO - Bundle already up-to-date
    17:41:40 - INFO - Guard::RSpec is running
    17:41:40 - INFO - Guard is now watching at '/Users/casiano/local/src/ruby/building_gems/bleigh_tutorial_to_building_gems/my-gem'
    [1] guard(main)>
    
This will get Guard up and running and you will now automatically run tests and re-bundle as you build your application.

Si ahora en una terminal modificamos uno de los ficheros vigilados:

$ touch spec/spec_helper.rb
Guard dispara la correspondiente acción, que en este caso es ejecutar RSpec:
17:50:28 - INFO - Running: spec
Run options: include {:focus=>true}

All examples were filtered out; ignoring {:focus=>true}
*

Pending:
  MyGem requires additional testing
    # Not yet implemented
    # ./spec/my_gem_spec.rb:5

Finished in 0.00062 seconds
1 example, 0 failures, 1 pending


Randomized with seed 46343

[1] guard(main)>

Running Guard makes the development feedback loop as tight and automatic as possible.

Enlaces Relacionados

Gemas

  1. crguezl / bleigh-tutorial-to-building-gems en GitHub

Testing

  1. Polishing Rubies (Part 3): Tools for Testing

Guard

  1. Guard en GitHub
  2. Guard Wiki
  3. Hire a Guard for Your Project
  4. Automate your application's development environment with Guard by Michael van Rooijen
  5. Guard Rspec
  6. guard-gitpusher
  7. Guard and Rack-livereload With Sinatra
  8. Guard is Your Best Friend Jeffrey Way NetTuts Screencast



Subsecciones
Casiano Rodriguez León 2015-06-18