capybara, poltergeist, phantomjs で js: true なテストをする
save_and_open_page や save_screenshot する場合には、 html の charset が設定されていないと日本語が文字化けてしまいました。 そういう場合には書きましょう。
<meta charset="UTF-8" />
まず install phantomjs (Ubuntu での例です)
$ wget https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-2.1.1-linux-x86_64.tar.bz2 $ sudo cp -ip phantomjs-2.1.1-linux-x86_64/bin/phantomjs /usr/local/bin/ $ phantomjs --version 2.1.1
Gemfile
group :test do gem "capybara" gem "launchy" # save_and_open_page するなら gem "poltergeist" end
rails_helper.rb
require "capybara/poltergeist" Capybara.javascript_driver = :poltergeist
sample feature spec
# sample_spec.rb require "rails_helper" RSpec.describe "Sample", :type => :feature do before do visit foo_path end feature "bar" do senario "baz", js: true do click_link "baz" # target: "_blank" な場合は別 window になる within_window(switch_to_window(windows.last)) do expect(current_path).to eq("/foo/bar/baz") expect(page).to have_content "some content" # save_page("save.html") # save_and_open_page save_screenshot "screenshot-#{DateTime.now}.png" # 全画面とりたい場合は full: true で save_screenshot("screenshot-#{DateTime.now}.png", full: true) end end end end
save_and_open_page で js, css も反映されたい場合、 assets が localhost で完結している場合には別途 rails s しておいて、 rails_helper.rb などに以下の様に設定しておくというのが簡単かなあと思いました。
Capybara.asset_host = "http://localhost:3000"