怖話はminitestに書き換えつつあるんですが、Bizerでは他の開発者に気を使ってrspecを使っています。

Bizerをrails4.1に上げたので、「ヒャッハー、デフォルトでtravel_toが使えるからtimecop削除できるぜー!」と思ったのですがrspecじゃそのままじゃ使えない。(クソがぁ

Before:

it 'coupon is expired.' do
  # FIXME: travel_to in rails 4.1
  Timecop.travel(2014, 5, 10, 0, 0, 0) do
    expect(expired_coupon_user.free_by_coupon?).to be_false
  end
end

After:

# spec/spec_helper.rb:
RSpec.configure do |config|
  config.include ActiveSupport::Testing::TimeHelpers
end
it 'coupon is expired.' do
  travel_to Time.new(2014, 5, 10, 0, 0, 0) do
    expect(expired_coupon_user.free_by_coupon?).to be_false
  end
end

今までTime.nowDate.todayを内部で使うメソッドはテストしやすいように

def metrix(now = Time.now); ... end

みたいに書いてたんですが、デフォルトで気軽にtravel_toが使えるならやらなくていいかな!

jenkins, rspec-railsの場合。

# Gemfile:
group :test do
  gem 'ci_reporter'
end

Rakefileの最終行に下記を追加する。

# Rakefile:
require 'ci/reporter/rake/rspec'

rake specの代わりにrake ci:setup:rspec specを実行するとspec/reports/以下にテスト結果のxmlができるので.gitignoreに追加しとく。

spec/reports/

jenkinsの設定

Build時にrake ci:setup:rspec specでxmlが出力されるようにしておく。怖話ではこんな感じ。

bundle install --binstubs
cp config/database.example.yml config/database.yml
rake db:migrate
rake ci:setup:rspec spec

Post-build Actions > Publish JUnit test result reportを追加し、spec/reports/*.xmlを入力。JUnitがこういうxml出すみたい。

下記のようなグラフが出るようになる。怖話ではこんな感じ。

画像を直リンできるので目につきやすいところに貼るのがいいかも。

怖話をRuby 1.9.3とRails 3.2.1にした。

アプリの動作には影響無く簡単に移行できると思いきや、shoulda-contextがrails 3.2から対応しないのでテストを全てRSpecに書き換えた。

rspecコマンド単体で実行した時とrake specした時で結果が違うのが少し気になるが・・・。

module Foo
  module Helpers
    def bar
      'unk'
    end
  end
end

こういうHelpersを

helpers do
  include Foo::Helpers
end

こういう風に使ってた場合。

RSpec.configure do |config|
  config.include Foo::Helpers
end
describe Foo::Helpers do
  context 'bar' do
    it 'should return unk' do
      bar.should eql('unk')
    end
  end
end

Spec::Runner.configでincludeするとテスト出来る。

LokkaはSinatraベースなので同じようにHelpersのテスト書ける。でもRspecややこしいな。config.includeのとことか。とTest::Unit, Shoulda信者が申しております。

Railsでguardを使う。(rspec)

# Gemfile:
group :test do
  gem 'rspec-rails'
  gem 'guard-rspec'

  # for Mac
  gem 'rb-fsevent'
  gem 'growl'
end
$ guard init rspec
$ guard start