RSpec for Ruby

作者: xr_hui | 来源:发表于2017-07-25 18:15 被阅读0次

    为什么写测试


    我们每天都在检查自己写的代码的正确性,往往我们会手动执行看看结果是否正确

    • 在界面手动测试
    • 在终端手动测试

    写测试的时间 < debug除错的时间

    手动测试很没效率,手动测试往往会重复许多相同工作,并且会对部分功能的测试有遗漏,当项目部分功能需要重构的情况下最能直接体现出测试的重要性

    什么是TDD


    TDD是测试驱动开发(Test-Driven Development)的英文简称,是敏捷开发中的一项核心实践和技术,也是一种设计方法论。TDD的原理是在开发功能代码之前,先编写单元测试用例代码,测试代码确定需要编写什么产品代码。TDD虽是敏捷方法的核心实践,但不只适用于XP(Extreme Programming),同样可以适用于其他开发方法和过程。

    先写测试再写功能实现

    这一点能够帮助你的API设计,从调用者的角度去思考API的设计

    什么是单元测试


    单元测试是指对软件中的最小可测试单元进行检查和验证

    基本上所有高级语言都有一个单元测试框架,套路基本上一致

    1. Setup 初始化工作
    2. Expercise 执行要测试的程序
    3. Verify 验证程序的运行状态是否和预期的一致
    4. Teardown 结束前的清理工作

    Ruby的Test::Unit

        class UserTest < Test::Unit::TestCase
    
            def setup
                @user = User.new
            end
    
            def test_user_status_when_init
                assert_equal @user.status, 'new'
            end
    
            def test_user_age_when_init
                assert_equal @user.discount, 0.9
            end
    
        end
    

    什么是RSpec


    Rspec是一种Ruby的测试领域特定语言

    • 比Test::Unit更好读,写的人更容易描述测试的目的
    • 写出来的测试文件是可执行的规格文件

    但是需要注意的是

    1. Rspec不是全新的测试方法
    2. Rspec是一种改良的测试单元框架
    3. Rspec由TDD衍生而来,改成为BDD(Behavior-driven development)

    RSpec的写法

        describe User do
            before do
                @user = User.new
            end
    
            context 'when init' do
                it 'should have default status is new' do
                    expect(@user.status).to eq('new')
                end
    
                it 'should have default discount is 0.9' do
                    expect(@user.discount).to eq(0.9)
                end
            end
        end
    

    RSpec给人的第一印象就是可读性非常好,看起来就像是说明书

    RSpec的语法


    学习RSpec主要也就是学习RSpec的语法

    describe和context(组织和分类)

    describe通常代表一个类别,describe可以内嵌于自身,内嵌时通常开头用'#'表示实例对象的方法,'.'表示类的方法

        describe User do
            describe '#age' do
                # ...
            end
        end
    
        describe 'Not user' do
            # ...
        end
    

    可以在describe内嵌多个context代表不同情境

        describe User do
            describe '#discount' do
                context 'when user is vip' do
                    # ..
                end
    
                context 'when user is not vip' do
                    # ..
                end
            end
        end
    

    每一个it就是一个小测试

        describe User do
            describe '#discount' do
                context 'when user is vip' do
                    it 'should discount 0.8 if total > 200 ' do
                        # ...
                    end
    
                    it 'should discount 0.7 if total > 300 ' do
                        # ...
                    end
                end
    
                context 'when user is not vip' do
                    it 'should discount 0.9 if total > 200 ' do
                        # ...
                    end
                end
            end
        end
    

    使用except(...).to 或 to_not来定义期望运行结果

        describe User do
            describe '#discount' do
                context 'when user is vip' do
                    it 'should discount 0.8 if total >= 200 ' do
                        user = User.new is_vip: true, consume: 200 
                        except(user.discount).to eq(0.8)
                    end
    
                    it 'should discount 0.7 if total >= 300 ' do
                        # ...
                    end
                end
    
                context 'when user is not vip' do
                    it 'should discount 0.9 if total >= 200 ' do
                        # ...
                    end
                end
            end
        end
    

    skip

    可以先跳过某个测试,或者是列出想要写的测试,有三种不同的写法

        describe User do
            describe '#discount' do
                context 'when user is vip' do
                    it 'should discount 0.8 if total >= 200 ' do
                        user = User.new is_vip: true, consume: 200 
                        except(user.discount).to eq(0.8)
                    end
    
                    it 'should discount 0.7 if total >= 300 ' do
                        # ...
                    end
    
                    # 使用it不带block
                    it 'skip this part with it but block'
    
                    # 使用skip
                    skip 'skip this part with skip' do
                    end
    
                    # 使用xit
                    xit 'skip this part with xit' do
                    end
    
                end
    
                context 'when user is not vip' do
                    it 'should discount 0.9 if total >= 200 ' do
                        # ...
                    end
                end
            end
        end
    

    跳过的测试将作为pending而不是sample,带跳过测试的输出结果如下

        Pending: (Failures listed here are expected and do not affect your suite's status)
    
          1) User#user_discount when user is vip skip this part with it but block
             # Not yet implemented
             # ./user_spec.rb:59
    
          2) User#user_discount when user is vip skip this part with skip
             # No reason given
             # ./user_spec.rb:61
    
          3) User#user_discount when user is vip skip this part with xit
             # Temporarily skipped with xit
             # ./user_spec.rb:64
    
        Finished in 0.00204 seconds (files took 0.10225 seconds to load)
        7 examples, 0 failures, 3 pending
    

    before和after

    • 类似于单元测试的setup和teardown
    • 搭配describe和context放在适当的位置
    • before(:each) 每段it之前执行
    • before(:all) 整段describe或context之前执行一次
    • after(:each) 每段it之后执行
    • after(:all)) 整段describe或context之后执行一次

    完整demo如下

        class User
    
            def initialize args
                @is_vip = args.include?(:is_vip) ? args[:is_vip] : true
                @consume = args.include?(:consume) ? args[:consume] : 0
            end
    
            # 获取用户的折扣
            def user_discount
                if @is_vip
                    if @consume >= 300
                        @discount = 0.7
                    elsif @consume >= 200
                        @discount = 0.8
                    end
                else
                    if @consume >= 300
                        @discount = 0.8
                    elsif @consume >= 200
                        @discount = 0.9
                    end
                end
                @discount
            end
    
            def set_vip vip
                @is_vip = vip
            end
    
            def set_consume consume
                @consume = consume
            end
    
        end
    
        describe User do
    
            describe '#user_discount' do
    
                context 'when user is vip' do
    
                    before(:all) do
                        @user = User.new is_vip: true
                    end
    
                    it 'should discount 0.8 if total >= 200' do
                        @user.set_consume 200
                        expect(@user.user_discount).to eq(0.8)
                    end
    
                    it 'should discount 0.7 if total >= 300' do
                        @user.set_consume 300
                        expect(@user.user_discount).to eq(0.7)
                    end
                
                    it 'skip this part with it but block'
    
                    skip 'skip this part with skip' do
                    end
    
                    xit 'skip this part with xit' do
                    end
    
                end
    
                context 'when user is not vip' do
    
                    before(:all) do
                        @user = User.new is_vip: false
                    end
    
                    it 'should discount 0.9 if total >= 200' do
                        @user.set_consume 200
                        expect(@user.user_discount).to eq(0.9)
                    end
    
                    it 'should discount 0.8 if total >= 300' do
                        @user.set_consume 300
                        expect(@user.user_discount).to eq(0.8)
                    end
                end
            end
    
        end
    

    使用命令rspec user_spec.rb -f documentation运行成功后的结果如下

        User
          #user_discount
            when user is vip
              should discount 0.8 if total >= 200
              should discount 0.7 if total >= 300
              skip this part with it but block (PENDING: Not yet implemented)
              skip this part with skip (PENDING: No reason given)
              skip this part with xit (PENDING: Temporarily skipped with xit)
            when user is not vip
              should discount 0.9 if total >= 200
              should discount 0.8 if total >= 300
    
        Pending: (Failures listed here are expected and do not affect your suite's status)
    
          1) User#user_discount when user is vip skip this part with it but block
             # Not yet implemented
             # ./user_spec.rb:59
    
          2) User#user_discount when user is vip skip this part with skip
             # No reason given
             # ./user_spec.rb:61
    
          3) User#user_discount when user is vip skip this part with xit
             # Temporarily skipped with xit
             # ./user_spec.rb:64
    
    
        Finished in 0.00195 seconds (files took 0.10213 seconds to load)
        7 examples, 0 failures, 3 pending
    

    let和let!

    let可以用来简化上述的before方法,需要用到时才初始化,并且在不同的单元测试之间,只会初始化一次,可以增加测试执行效率。使用let,可以比before更清楚看到哪个是主要成分,也不需要本来的@

    let!则会在测试一开始就先初始化一次,而不是需要才初始化

        class User
    
            def initialize args
                @is_vip = args.include?(:is_vip) ? args[:is_vip] : true
                @consume = args.include?(:consume) ? args[:consume] : 0
            end
    
            # 获取用户的折扣
            def user_discount
                if @is_vip
                    if @consume >= 300
                        @discount = 0.7
                    elsif @consume >= 200
                        @discount = 0.8
                    end
                else
                    if @consume >= 300
                        @discount = 0.8
                    elsif @consume >= 200
                        @discount = 0.9
                    end
                end
                @discount
            end
    
            def set_vip vip
                @is_vip = vip
            end
    
            def set_consume consume
                @consume = consume
            end
    
        end
    
        describe User do
    
            describe '#user_discount' do
    
                context 'when user is vip' do
    
                    let(:user) do
                        user = User.new is_vip: true
                    end
    
                    it 'should discount 0.8 if total >= 200' do
                        user.set_consume 200
                        expect(user.user_discount).to eq(0.8)
                    end
    
                    it 'should discount 0.7 if total >= 300' do
                        user.set_consume 300
                        expect(user.user_discount).to eq(0.7)
                    end
                
                    it 'skip this part with it but block'
    
                    skip 'skip this part with skip' do
                    end
    
                    xit 'skip this part with xit' do
                    end
    
                end
    
                context 'when user is not vip' do
    
                    let!(:user) do
                        user = User.new is_vip: false
                    end
    
                    it 'should discount 0.9 if total >= 200' do
                        user.set_consume 200
                        expect(user.user_discount).to eq(0.9)
                    end
    
                    it 'should discount 0.8 if total >= 300' do
                        user.set_consume 300
                        expect(user.user_discount).to eq(0.8)
                    end
                end
            end
    
        end
    

    相关文章

      网友评论

        本文标题:RSpec for Ruby

        本文链接:https://www.haomeiwen.com/subject/jziwkxtx.html