LoginSignup
149
165

More than 5 years have passed since last update.

Rails RSpecの基本 ~導入編~

Posted at

RSpecはRubyのテストフレームワークです。

インストール

下記をGemfileに記述してbundle install。
RSpecはRailsアプリケーションにデフォルトでは入っていないので、RSpecとその他いくつかのヘルパーをインストール。

Gemfile
group :development, :test do
  gem 'rspec-rails', '~> 2.14.0'
  gem 'factory_girl_rails', '~> 4.2.1'
end

group :test do
  gem 'faker', '~> 1.1.2'
  gem 'capybara', '~> 2.1.0'
  gem 'database_cleaner', '~> 1.0.1'
  gem 'launchy', '~> 2.3.0'
  gem 'selenium-webdriver', '~>2.45.0'
end

selenium-webdriverはバージョンを最新にしなければ、うまく動かない可能性があるので注意。

RSpecの設定

$ bundle exec rails generate rspec:installを実行。
下記を生成。

create  .rspec
create  spec
create  spec/spec_helper.rb

RSpecの出力をドキュメント形式で読みやすくする。

/.rspec
--format documentation

を追記。

不要なファイルを生成しないための設定

/config/application.rb
config.generators do |g|
  g.test_framework :rspec,
    fixtures: true,
    view_specs: false,
    helper_specs: false,
    routing_specs: false,
    controller_specs: true,
    request_specs: false
  g.fixture_replacement :factory_girl, dir: "spec/factories"
end

development環境で使われているデータベース構造をtest環境へクローンする。

$rake db:test:clone

*WARNINGが出たが、とりあえず動く。

この点については下記を参照。
Railsで既存のデータベースを使ったWeb API開発のハマりどころ
RSpecでテストデータベースの準備

$bundle exec rake db:test:prepare

$bundle exec rake db:migrate RAILS_ENV=test
も同様の役割を持つコマンドらしく、バージョンによってころころ変わる。

なお、データベースの構造を変更したときは、cloneコマンドでtestデータベースにその変更を反映させなければならない。

参考

Everyday Rails - RSpecによるRailsテスト入門
を参考にしております。詳細な説明・使い方を知りたい方はオススメです。

使えるRSpec入門・その1「RSpecの基本的な構文や便利な機能を理解する」
RSpecに関しましてはこちらも参考になります。その1~その4まであります。

149
165
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
149
165