h3pei.tech
お仕事のご依頼
2014-05-24

RSpec + Guardで自動テスト実行環境を作る

タイトル通り。
TDD のお試し環境として自動でテストが実行される環境を作りたかったので、構築した。

1.作業ディレクトリを作る

mkdir fizzbuzz
cd fizzbuzz

2.Gemfile を作る

bundle init

3.Gemfile を編集する

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

gem 'rspec'
gem 'guard'
gem 'guard-rspec'
gem 'spring'

4. Gem を格納するディレクトリを作る

mkdir vendor

5. Gem をインストールする

$ bundle install --path vendor/ 
Fetching gem metadata from https://rubygems.org/.........
Fetching additional metadata from https://rubygems.org/..
Resolving dependencies...
Installing timers 1.1.0
.
.
.
Your bundle is complete!
It was installed into ./vendor

6.Guard の設定を行う

# 以下のコマンドでGuardfileが作られる
$ bundle exec guard init

7.Guard ファイルを編集する
※ちゃんと調べていないので、記述に誤りがある可能性あり。

  • 不要な行を削除
  • guard :rspec…から始まる行に cmd オプションを追加
  • ルート直下のファイルを watch するように設定追加
# A sample Guardfile
# More info at https://github.com/guard/guard#readme

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

8.テストファイルを作成する

  • RSpec のテストファイルは spec ディレクトリを作成してその配下に作成する
  • spec_helper.rb には共通の設定を書くとよいらしい(今回は不要だったかも)
  • fizzbuzz.rb のテストファイルである fizzbuzz_spec.rb を作成
mkdir spec
touch spec/spec_helper.rb
touch spec/fizzbuzz_spec.rb

9.fizzbuzz.rb を編集する

fizzbuzz.rb に適当なメソッドを作成する

# 1を返すだけのsampleメソッドを作成
def sample
  1
end

10. fizzbuzz_spec.rb を編集する

require './fizzbuzz.rb'

describe 'Hello rspec' do

  # 成功する
  it 'sample1' do
    sample.should == 1
  end

  # 失敗する
  it 'sample2' do
    sample.should == 2
  end

end

11. spec_helper.rb を編集する ここには共通の設定などを書くらしい

require 'bundler'
Bundler.require

12.Guard を動かす

$ bundle exec guard start
20:04:02 - INFO - Guard is using Tmux to send notifications.
20:04:02 - INFO - Guard is using TerminalTitle to send notifications.
20:04:02 - INFO - Guard::RSpec is running
20:04:02 - INFO - Guard is now watching at '/Users/hiroki/work/ruby/fizzbuzz'
[1] guard(main)>

この状態で、fizzbuzz_spec.rb などを上書き保存してみる。

Failures:

   1) Hello rspec sample2
      Failure/Error: sample.should == 2
             expected: 2
                         got: 1 (using ==)
     # ./spec/fizzbuzz_spec.rb:10:in `block (2 levels) in <top (required)>'

Finished in 0.00047 seconds
2 examples, 1 failure

Failed examples:

rspec ./spec/fizzbuzz_spec.rb:9 # Hello rspec sample2

OK。テストが自動で実行され、期待通りテストが1つだけ失敗した。
これで手軽な TDD 環境ができた。

h3pei's icon

h3pei

フリーランスのソフトウェアエンジニア。Ruby / Rails アプリケーションの開発が得意領域。設計・実装・運用まで含めてプロダクト開発が好きです。

Questalという目標達成コミュニティサービスを開発しました。仲間と一緒に目標達成に取り組みたい方はぜひご利用ください。

お仕事のご依頼
GitHubnoteX

関連記事