LoginSignup
79
73

More than 5 years have passed since last update.

Poltergeist + Rspec + Capybara導入のメモ

Posted at

PoltergeistをRailsの統合テストに組み入れた。

Railscasts#391 http://railscasts.com/episodes/391-testing-javascript-with-phantomjs?view=asciicast を参考にした。

しかし、いくつかRailscastsには書かれていない変更点があった。

Poltergeistの設定

Poltergeistを組み入れて

$ rspec

したところ、

An error occurred in an after hook
  Capybara::Poltergeist::TimeoutError: Timed out waiting for response to …

というエラーが発生した。
Poltergeistの説明書( https://github.com/jonleighton/poltergeist/issues/169 )を読んだところ、

spec_helper.rb
Capybara.javascript_driver = :poltergeist
Capybara.register_driver :poltergeist do |app|
  Capybara::Poltergeist::Driver.new(app, :js_errors => false, :timeout => 60)
end

とすればよいとわかった。各オプションについて以下に説明する。

:js_errors

:js_errors => falseにしたのはCapybara::Poltergeist::JavascriptError: というエラーを防ぐため。JSのエラーはよくあることなのだが、エラーが出るたびにCapybaraを止めるのは時間の無駄。ということで、JSのエラーは無視することにした。

:timeout

Timeoutはデフォルトでは30秒。しかし、ログインのような時間のかかるDB走査がある場合、30秒以上時間がかかることがある。そのため、60秒に設定した。

データベースの問題

Factory Girlで作ったはずのモデルが読み込めなかったりするのは、1つ1つのテストが別のデータベーストランザクションで行われいるのが原因。……とRyan Bates( http://railscasts.com/episodes/391-testing-javascript-with-phantomjs?view=asciicast )が言っている。

なので、ActiveRecord::Baseをオーバーライドして修正。

/spec/support/share_db_connection.rb
class ActiveRecord::Base
  mattr_accessor :shared_connection
  @@shared_connection = nil

  def self.connection
    @@shared_connection || retrieve_connection
  end
end

# Forces all threads to share the same connection. This works on
# Capybara because it starts the web server in a thread.
ActiveRecord::Base.shared_connection = ActiveRecord::Base.connection

これでOK。

79
73
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
79
73