当前位置 : 主页 > 网页制作 > HTTP/TCP >

Rails rspec document

来源:互联网 收集:自由互联 发布时间:2021-06-16
创建: 2019/10/09 https://rspec.info/documentation/ 安装与使用 Gemfile group :development, :test do gem ‘ rspec-rails ‘ , ‘ ~ 3.8 ‘ end bash rails g rspec:install 生成spec文件 # RSpec hooks into built-in generators $ rails

创建: 2019/10/09

 

https://rspec.info/documentation/

 

安装与使用  Gemfile

 

group :development, :test do
  gem rspec-rails, ~> 3.8
end

 

 

 bash  
rails g rspec:install

 

 生成spec文件

 

# RSpec hooks into built-in generators
$ rails generate model user
      invoke  active_record
      create    db/migrate/20181017040312_create_users.rb
      create    app/models/user.rb
      invoke    rspec
      create      spec/models/user_spec.rb

# RSpec also provides its own spec file generators
$ rails generate rspec:model user
      create  spec/models/user_spec.rb

# List all RSpec generators
$ rails generate --help | grep rspec

 

 

 运行

 

# Default: Run all spec files (i.e., those matching spec/**/*_spec.rb)
$ bundle exec rspec

# Run all spec files in a single directory (recursively)
$ bundle exec rspec spec/models

# Run a single spec file
$ bundle exec rspec spec/controllers/accounts_controller_spec.rb

# Run a single example from a spec file (by line number)
$ bundle exec rspec spec/controllers/accounts_controller_spec.rb:8

# See all options for running specs
$ bundle exec rspec --help

 

 ● 避免每次都输入bundle exec

bundle binstubs rspec-core

 

 

    基本方法  describe

 给测试增加命名空间 

RSpec.describe ‘sample test‘ do

    ...
end

  ● 除了最外侧的,其他的可以省略 RSpec. 

RSpec.describe sample test do
    describe A do
        ...
    end
end

  ● 参数除了字符串,也可以是class

RSpec.describe Sample do
    ...
end

 

 

 it

 测试的基本单位(example)

RSpec.describe sample test do
    it sample it do
    end
end

 ● 同一个describe内部也可以有多个it

describe sample do
    it ... { ... }
    it ... { ... }
    ...
end

 

 ● 同一个it内可以有多个expect

describe sample do
    it ... {
        expect(...).to ...
        expect(...).to ...
        expect(...).to ...
    end
end

 

 

 except

 描述期待的情况

RSpec.describe sample test do
    it 1+1=2 do
        expect(1+1).to eq 2
    end
end

 

 context

 和describe一样

 ● 主要用于分条件测试,相当于if

 before 

 每次example(it)前都会呼出

 在里面放上测试时通用的数据等

 ● 内部用实例变量(@...)才能传到it

 ● 嵌套的descirbe/context, 每一个一个都会从根开始呼出before

RSpec.describe Book do
  before do
    @book = Book.create(title: a)
    puts "UUID A"
  end
  describe #title do
    before { puts "UUID B" }
    it title a do
      expect(@book.title).to eq(a)
    end
  end

  describe #title_ do
    before { puts "UUID C" }
    it title a do
      expect(@book.title).to eq(a)
    end
  end
end

 结果

UUID A
UUID B
UUID A
UUID C

 

 

 

 let

  参数作为变量使用,值为let代码块的返回值

 lazyLoad   

let(:...) { ... }
let(:...) do ... end

 

 

 let!    subject     shared_examples    shared_context    pending    skip       matcher                     mock                     feature
网友评论