RSpec功能测试

    (1)功能测试需要用到Capybara、DatabaseCleaner、Launchy

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

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

例:

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: '[email protected]'
            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 '[email protected]'
    end
end

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

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

    (6)功能测试中,一个测试用例或场景中可以包含多个期望

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

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

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

    (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


你可能感兴趣的:(测试,Ruby,功能测试,rspec)