LoginSignup
7
6

More than 5 years have passed since last update.

RailsじゃないRspec3環境を構築してGuardで自動実行する方法

Last updated at Posted at 2015-05-19

はじめに

RailsじゃないRspec3環境を構築する方法 という記事でRailsじゃないプロジェクトでrspec3を導入する方法が紹介されています。
このページを参考にしてrspecをスムーズに導入できましたが、しばらく作業していたら次はrspecコマンドを実行するのが面倒になってきました。
guardを導入してファイルが更新されたタイミングで自動的にテストが走るように設定したので、その方法をメモします。

前提

元記事 と同じ環境を前提としています。
つまりbundlerでgemの管理をして、rspec3以上を導入して、bundle exec rspecでテストが動くような状態です。
ファイル構成は以下のとおりです。

rspec_test
├── Gemfile
├── Gemfile.lock
├── lib
│   └── hello.rb
└── spec
    ├── hello_spec.rb
    └── spec_helper.rb

手順

1. guard-rspecを導入

guard-rspec というgemを導入します。

Gemfile
# A sample Gemfile
source "https://rubygems.org"

gem 'rspec', '>= 3.0.0'
+ gem 'guard-rspec', require: false

2. Guardfile を生成

guard init rspec を実行します。Guardfileが作られます。

3. Guardfile を編集

Guardfileを以下のように編集します。

Guardfile
guard :rspec, cmd: 'bundle exec rspec' do
  watch(%r{^spec/.+_spec\.rb$})
  watch(%r{^lib/(.+)\.rb$})     { |m| "spec/#{m[1]}_spec.rb" }
  watch('spec/spec_helper.rb')  { "spec" }
end

例えば、hello.rbが変更された場合、bundle exec rspec hello_spec.rbが実行されます。

cmd というオプションで実際に実行するコマンドを指定します。bundler経由でrspecを実行しているので bundle exec rspecと指定する必要があります。

4. 実行

ターミナルで bundle exec guard を実行するとファイル監視が始まります。Ctrl-Dで終了できます。

5. (おまけ) 通知を表示する

実行後にMac OSXの通知センターを使って結果を表示するには terminal-notifier-guard を使います。(Mac以外の人は他の通知gem用を使ってください。)

  1. terminal notifierをインストール brew install terminal-notifier
  2. Gemfileにterminal-notifier-guardを追加して、guardを再起動。
Gemfile
# A sample Gemfile
source "https://rubygems.org"

gem 'rspec', '>= 3.0.0'
gem 'guard-rspec', require: false
+ gem 'terminal-notifier-guard', '~> 1.6.1'
7
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
6