RSpec功能测试

    (1)功能测试须要用到Capybara、DatabaseCleaner、Launchy数据库

    (2)Capybara使用例如click_link、fill_in和visit,来模拟用户在浏览器中和应用程序交互的过程浏览器

    (3)功能测试应该用feature替换掉describe,用scenario替换itruby

例:dom

feature 'User management' do
    scenario "adds a new user" do
        admin = create(:admin)
        visit root_path
        click_link 'Log In'
        fill_in 'Email', wirh: admin.email
        fill_in 'Password', with: admin.password
        click_button 'Log In'
        visit root_path
        expect do
            click_link 'Users'
            click_link 'New User'
            fill_in 'Email', with: 'newuser@example.com'
            find('#password').fill_in 'Password', with: 'secret123'
            find('#password_confirmation').fill_in 'Password confirmation', with:‘secret123’
            click_button 'Create User'
        end.to change(User, :count).by(1)
        expect(current_path).to eq users_path
        expect(page).to have_content 'New user created'
        within 'h1' do
            expect(page).to have_content 'Users'
        end
        expect(page).to have_content 'newuser@exaple.com'
    end
end

    (4)find('#password')经过dom元素的id查找,咱们还能够经过XPath路径查找,或者使用普通的文本查找,例如click_link 'Users',若是没找到测试会报错测试

    (5)within用来限定查找指定区域,within 'h1'表示只在<h1>标签中查找ui

    (6)功能测试中,一个测试用例或场景中能够包含多个指望code

    (7)Capybara 2.0对DSL句法作了一些该表,用功能测试替换了请求测试,请求测试仅仅用于API接口测试接口

    (8)feature和scenario仅用与功能测试,功能测试中用background对应before,given对应let,同时feature不能嵌套事务

    (9)Launchy用于把功能测试当前渲染也面保存到一个临时文件夹,而后在系统默认浏览器中打开ip

    (10)Launchy使用方法,在想看页面的地方加入save_and_open_page

    (11)Capybara默认的Web启动是Rack::Test,没法处理JavaScript,能够使用Selenium来模拟JavaScript

    (12)Selenium使用,只须要在须要js交互的scenario的block前加上js: true就能够了

    (13)使用Selenium的同时,须要是用Database Cleaner处理数据库事务,为了将事务清理干净

    (14)Database Cleaner配置:

spec/spec_helper.rb

RSpec.configure do |config|
    config.use_transactional_fixtures = false
    config.before(:suite) do
        DatabaseCleaner.strategy = :truncation
    end
    config.before(:each) do
        DatabaseCleaner.start
    end
    config.after(:each) do
        DatabaseCleaner.clean
    end
end
spec/support/shared_db_connection.db
class ActiveRecord::Base
    mattr_accessor :shared_connection
    @@shard_connection = nil
    def self.connection
        @@shared_connection || retrieve_connection
    end
end
ActiveRecord::Base.shared_connection = ActiveRecord::Base.connection
相关文章
相关标签/搜索