Rspec 3.1
have(n) 利用時には rspec-collection_matchers が必用
group :test do
gem "rspec"
gem "rspec-rails"
gem 'rspec-collection_matchers'
end
$ rails g rspec:model model_name
customer_spec.rb
# coding: utf-8
require 'rails_helper'
RSpec.describe Customer, :type => :model do
it "is invalid without password" do
expect(Customer.new(email: nil)).to have(1).errors_on(:email)
end
end
テスト用DBの準備
- developmentの内容をtestに移す
$ rake db:migrate
$ rake db:test:prepare
Factoryを利用する
spec/models/model_spec.rb
RSpec.describe Model, :type => :model do
it "is invalid without email" do
expect(build(:invalid_attr)).to have(1).errors_on(:email)
end
end
guard-spec によるテスト自動化
group :test do
...
gem 'guard-rspec'
end
$ guard init rspec
$ guard
Spork によるテスト高速化
annotate_models によるスキーマ可視化
group :development do
...
gem 'annotate'
end
$ cd /path/to/app
$ annotate
- スキーマの情報がモデルに追加される
app/models/model.rb
# == Schema Information
#
# Table name: members
#
# id :integer not null, primary key
...
FactoryGirl
導入
group :test do
...
gem 'factory_girl_rails'
end
spec/spec_helper.rb
# これがないとrspec実行時にuninitialized constant FactoryGirlのエラー
require 'factory_girl_rails'
RSpec.configure do |config|
...
config.include FactoryGirl::Syntax::Methods
end
Factoryを定義
spec/factories/model.rb
# coding: utf-8
FactoryGirl.define do
factory :invalid_email, class: Model do
email nil
end
end
i18nのdeprecated警告を解消
- Rails 4.0.2から以下の警告が発生
- rspec実行時でも発生
[deprecated] I18n.enforce_available_locales will default to true in the future. If you really want to skip validation of your locale you can set I18n.enforce_available_locales = false to avoid this message.
config/application.rb
module YourApplication
class Application < Rails::Application
...
I18n.enforce_available_locales = false
end
end