這里,我的集成測試用的是capybara+rspec
一、有Gemfile里添加gem引用
? gem 'rspec-rails', '~> 3.5'
? gem 'factory_girl_rails'
? gem 'database_cleaner' # 清理測試數據
? gem 'capybara'
? gem 'capybara-screenshot'? # 保存測試錯誤的頁面
? gem 'selenium-webdriver', '~>2.53.4' #提供網頁支持
? gem "chromedriver-helper"?? #chrome瀏覽器支持
二、配置
? 在spec_helper.rb文件里添加如下配置:
? config.before(:each) do
??????? DatabaseCleaner.strategy = :transaction
??? end
?? config.after(:all, type: :feature) do
??????? DatabaseCleaner.clean
?? end
三、測試
?? rails generate rspec:install? #產生spec文件夾
?? 在spec的文件夾里新建文件夾:integration,在這個文件夾里存放集成測試的文件代碼。
?? 在這個文件里新建一個login_spec.rb,這查寫測試登錄的代碼:
?? require 'rails_helper'
? # 使用chrome瀏覽器
?? Capybara.register_driver :chrome do |app|
????? Capybara::Selenium::Driver.new(app, :browser => :chrome)
?? end
?? Capybara.default_driver = :chrome
?? Capybara.ignore_hidden_elements = false #這樣隱藏的element也能進行操作
?? RSpec.configuration.include(IntegrationHelper)
RSpec.feature 'integration', type: :feature do
?? before(:all) do
????? create(:user)
?? end
?? after(:all) do
????? @user.destroy if @user# with create in before(:all), it is not in a transaction
?? end
?? describe "登錄、修改密碼、退出", :type => :feature do
?? describe 'GET /' do
?? scenario 'sign_in and sign_out' do
????? within('#new_user') do
???????? fill_in 'user[email]', :with => '登錄名'
???????? fill_in 'user[password]', :with => "錯的密碼"
????? end
????? click_button '提交'
????? expect(page).to have_content '郵箱或密碼錯誤'
????? within('#new_user') do
???????? fill_in 'user[email]', :with => '登錄名'
???????? fill_in 'user[password]', :with => "正確的密碼"
????? end
???? click_button '提交'
????? expect(page).to have_content '登錄成功后頁面包含的內容'
?? end
?? end
?? end
end
四、運行測試
運行bundle exec rspec spec/integration,這里只是運行這個目錄下的測試,也可以用bundle exec rspec運行所有的測試。這時就應該能夠自動打開chrome瀏覽器,并可以看到效果了。
注意事項:啟動不了瀏覽器,可能是因為selenium-webdriver或chrome版本的問題,可以更新一下版本。