LoginSignup
13
16

More than 5 years have passed since last update.

RSpecテスト環境 設定 メモ _φ(・・*)

Last updated at Posted at 2015-08-05

RSpecをはじめる時、設定とか調べて回ったりしたので、
やったことまとめました

環境

・Rails 4.1.4
・ActiveRecord 4.1.4
・Mongoid 4.0.0
・Rspec 3.1

Gemfile



gem 'rails'
gem 'mysql2'
gem 'mongoid', '4.0.0'

group :development do
  gem 'guard-rspec'            # ファイルが変更されたらRsepcを自動実行
end

group :test do
  gem 'database_cleaner', '~> 1.3.0' # テスト実行後にDBをクリア
  gem 'capybara', '~> 2.4.3'         # ブラウザでの操作をシミュレートしてテストができる
  gem 'simplecov', :require=>false   # テストカバレッジ(テストカバー率)
end

group :development, :test do
  gem 'rspec-rails', '~> 3.1.0'            # Rails用機能を追加するRSpecラッハー
  gem 'factory_girl_rails', '~> 4.4.1'     # テストデータの生成
  gem 'spring-commands-rspec', '~> 1.0.2'  # RspecなどでRailsをプリロードする
  gem 'shoulda-matchers'                   # RSpecで使える便利なマッチャー集(ActiveRecord)
  gem 'mongoid-rspec'                      # RSpecで使える便利なマッチャー集(Mongoid)
end

$ bundle install

基本設定ファイル rails_helper.rb +α

下記を実行すると必要な設定ファイルなどが作成されます

$ bundle exec rails g rspec:install

RSpecに関する設定はこのrails_helper.rbに書いていきます。

spec/rails_helper.rb
ENV["RAILS_ENV"] ||= 'test'
require 'spec_helper'
require File.expand_path("../../config/environment", __FILE__)
require_relative "../lib/monkey_patches/active_record"
require 'rspec/rails'
require 'simplecov'
SimpleCov.start

require 'factory_girl'
require 'shoulda-matchers'
require 'database_cleaner'

Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }

ActiveRecord::Migration.maintain_test_schema!

RSpec.configure do |config|
  # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
  config.fixture_path = "#{::Rails.root}/spec/fixtures"

  config.include Devise::TestHelpers, type: :controller

  # If you're not using ActiveRecord, or you'd prefer not to run each of your
  # examples within a transaction, remove the following line or assign false
  # instead of true.
  config.use_transactional_fixtures = true

  config.infer_base_class_for_anonymous_controllers = false
  config.order = 'random'
  config.include FactoryGirl::Syntax::Methods

  config.before(:all) do
    FactoryGirl.reload
  end


  # テスト実行後にDBをクリア
  config.before(:suite) do
    DatabaseCleaner.clean_with(:truncation,{:except => %w{categories jobs initials job_positions}})
    DatabaseCleaner.strategy = :transaction
  end

  config.before :each do
    DatabaseCleaner[:mongoid].start
    DatabaseCleaner.start
  end

  config.after :each do
    DatabaseCleaner[:mongoid].clean
    DatabaseCleaner.clean
  end


  config.infer_spec_type_from_file_location!
end
spec/support/factory_firl.rb
RSpec.configure do |config|
  config.include FactoryGirl::Syntax::Methods
end
spec/support/mongoid.rb
RSpec.configure do |config|
  config.include Mongoid::Matchers, type: :model
end

テストDB用意

config/database.yml
test:
  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: website_test
  username: root
  password:
config/mongoid.yml
test:
  sessions:
    default:
      database: website_test
      hosts:
        - localhost:27017
      options:
        read: primary
        # In the test environment we lower the retries and retry interval to
        # low amounts for fast failures.
        max_retries: 1
        retry_interval: 0

FactoryGirl作成(テストデータ作成用)

$ rails g factory_girl:model ModelName

※詳しい書き方は、次の記事がとてもわかり易かったです
Factory Girl Railsのチートシート - Rails Webook

テストコードを書く

$ rails g rspec:model ModelName

テストコードの書き方下記にまとめました
RSpec書き方例/サンプルメモ(調べた書いたメモ) - Qiita

テスト実行

Guard (テストコードを修正すると自動実行)

$ guard init rspec 

Guardfile


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

  watch(%r{^app/(.+)\.rb$}) { |m| "spec/#{m[1]}_spec.rb" }
  watch(%r{^app/(.*)(\.erb|\.slim)$}) { |m| "spec/#{m[1]}#{m[2]}_spec.rb" }
  watch(%r{^spec/factories/(.+)\.rb$}) { 'spec/factories_spec.rb' }
  watch(%r{^spec/support/(.+)\.rb$}) { 'spec' }
  watch('config/routes.rb') { 'spec/routing' }
  watch('app/controllers/application_controller.rb')  { 'spec/controllers' }
end

※guard設定ファイルの書き方参考
http://qiita.com/unosk/items/c2e2bbc31d97e92803dc

guard立ち上げてテストファイル修正すると
自動でテストを該当箇所から走らせてくれる状態に。
Enterをおせば、全てのテストコードを実行してくれます

$ bundle exec guard 

特定のテストを実行

$ rpec spec/models/test_spec.rb:7

参考/関連リンクなど

※ バージョンの違いがあるので注意
- RSpecの入門とその一歩先へ ~RSpec 3バージョン~ - Qiita

※ mongoid使ってる時は、、
- 【RSpec】非ActiveRecord環境でActiveRecord::ConnectionNotEstablishedが出たときの対処法 - Qiita

続きは、、

続きは、下記にまとめました
RSpec書き方例/サンプルメモ(調べた書いたメモ) - Qiita

13
16
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
13
16