单元测试-rspec

1.部分语法

discible 和context

帮助组织分类,可任意折叠,参数可以是一个类别或者字串描述

describe Order do
  describe "#amount" do
    context "when user is vip" do
     # ...
    end

   context "when user is not vip" do
      # ...
    end
  end
end

一般来说,最外层是想要测试的类别,下一层是哪个方法,最后一层是哪一个情景

it 和 expect

每个it都是一小段测试,在里面用expect(...).to 来设定期望

describe Order do
  describe "#amount" do
    context "when user is vip" do
      
      it "should discount five percent if total >= 1000" do
        user = User.new( :is_vip => true )
        order = Order.new( :user => user, :total => 2000 )
        expect(order.amount).to eq(1900)
      end

    end
  end
end

before 和 after

  1. before(:each) 每段it之前执行,默认写 before 就是 before(:each)。
  2. before(:all) 整段describe前只执行一次, 尽量不要用
  3. after(:each) 每段it之后执行
  4. after(:all) 整段describe后只执行一次
    describe Order do
        describe "#amount" do

            context "when user is vip" do
              before(:each) do
                  @user = User.new( :is_vip => true )
                  @order = Order.new( :user => @user )
              end

              it "should discount five percent if total >= 1000" do
                @order.total = 2000
                expect(@order.amount).to eq(1900)
              end
            end
        
            context "when user is not vip" { ... }
        end
    end

let 和let!

let 用于简化上述的before ,并且支援lazy evaluation 和memoized,即有需要才开始,并且不同的测试单元之间只会初始化一次,可以增加测试执行效率

   #let! 会在测试一开始就先初始一次
    describe Order do
        describe "#amount" do
            context "when user is vip" do
              let(:user) { User.new( :is_vip => true ) }
              let(:order) { Order.new( :user => @user ) }
            end
         end
    end

specify 和 example 都it 的同义字

Matcher

expect(...).to 后面接各种Matcher 除了eq以外还有

  1. expect { ... }.to raise_error #测异常
  2. expect { ... }.to raise_error(ErrorClass)
  3. expect { ... }.to raise_error("message")
  4. expect { ... }.to raise_error(ErrorClass, "message")
  5. expect(JobClass).to have_been_enqueued.at_least(1) #测job

2.Rails中的测试

分类

  1. Model测试
  2. Controller测试
  3. View测试
  4. Helper测试
  5. Route测试
  6. Request测试

1.安装Repec-Rails

1.在Gemfile中加上

 gem 'rspec-rails', :group => [:development, :test]

执行:

    bundle
    rails g rspec:install

装完rspec-rails后,rails g model 或者controller 就会顺道建立对应的Spec档案

你可能感兴趣的:(单元测试-rspec)