LoginSignup
9
9

More than 5 years have passed since last update.

Rails4.1 with zeusでrspec3使おうとしたらいろいろハマった

Posted at

Rails4.0.xとrspec2ではいろいろやってましたが久しぶりに新しいアプリ作ってテスト書こうとしたらいろいろハマったのでメモしておきます。


使おうとしてるgem(ツール)

  • zeus
  • rails(4.1.4)
  • rspec-rails(3.0.2)
  • capybara(2.4.1)
  • database_rewinder(0.2.0)
  • factory_girl_rails(4.4.0)

rspec:install

まず、下記コマンドでrspecに必要なものをgenerateします。

$ bundle exec rails g rspec:install

.rspec
spec/spec_helper.rb
spec/rails_helper.rb

rspec-railsの3系からrails_helper.rbというのが作られるようになりました。

spec/rails_helper.rbにRails特有の設定を書き、spec/spec_helper.rbにRSpecの全体的な設定を書くようにするのが良いようです。

これまで*_spec.rbの先頭に

require 'sepc_helper'

と書いていたかと思いますが、3系からはそこを

require 'rails_helper'

に書き換える必要があります。

ちなみにこの時作られる.rspec内のデフォルトの記述の--warningsというのが非常に邪魔なログを吐きまくるので消しておくことをオススメします。

rails_helper.rbとspec_helper.rb

さて、ここからがいろいろダルかったのですが、、
だらだら書くと読む気失くなると思うので最終的なrails_helper.rbとspec_helper.rbを載せておきます。

spec/spec_helper.rb

require 'factory_girl_rails'
require 'database_rewinder'
require 'rspec/rails'

RSpec.configure do |config|
  config.order = 'random'

  config.before(:suite) do
    FactoryGirl.reload
    DatabaseRewinder.clean_all
  end

  config.before(:each) do
    DatabaseRewinder.start
  end

  config.after do
    DatabaseRewinder.clean
  end

  config.include FactoryGirl::Syntax::Methods
end

spec/rails_helper.rb

ENV["RAILS_ENV"] ||= 'test'
require 'spec_helper'
require File.expand_path("../../config/environment", __FILE__)

#require 'rspec/rails'

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

ActiveRecord::Migration.maintain_test_schema!

RSpec.configure do |config|
  config.fixture_path = "#{::Rails.root}/spec/fixtures"

  config.use_transactional_fixtures = true

  config.infer_spec_type_from_file_location!
end

 

これ、require 'rspec/rails'をspec_helper.rbかrails_helper.rbのどちらに書くかで、zeusではしらす時の挙動が変わるというのが超ダルいポイント。。

$ zeus test spec

このコマンドでテストを走らせたいときは
spec/spec_helper.rbにrequire 'rspec/rails'を書く。
$ bundle exec rspec

このコマンドでテストを走らせたいときは
spec/rails_helper.rbにrequire 'rspec/rails'を書く。

という。。辛たん。
zeusを使ってるかどうかで条件分岐させられるかもですが、調べられてません。
一旦私は普段はzeus頼みでやってるのでこんなかんじで。

その他ハマったところ。。。

上記の通り書けばいけると思いますが、ハマったポイントを。
どちらでrequireすべきかというところでハマりました。

undefined method `configure' for RSpec:Module (NoMethodError)
spec_helper.rb:21:in `block in <top (required)>': uninitialized constant FactoryGirl (NameError)

こういうのはすべてrequireできていないことによるエラーです。
factory_girlやdatabase_reqinderなどをspec_helper.rb内でrequireしているかもう一度確かめてみてください。

9
9
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
9
9