zoukankan      html  css  js  c++  java
  • rspec的一些常见用法

    这里讲了如何安装rspec,安装使用rspec

    下面介绍一下rspec中常见的使用方法。

    下面是一个最简单的测试用例,判断true是不是等于true,should_be是旧的用法,新用法推荐使用expect()

    it "is true when true" do
        true.should be_true
    end
    #新用法
    it "is true when true" do
        expect(true).to be_true
    end
    
    

    一,测试models中的方法

    1,测试实例方法

    #spec/models/contact_spec.rb

    def name
        [firstname, lastname].join(' ')
    end

    #spec/models/contact_spec.rb
    it "returns a contact's full name as a string" do
      contact = Contact.new(firstname: 'John', lastname: 'Doe',
                            email: 'johndoe@example.com')
      expect(contact.name).to eq 'John Doe'
    end

    测试相等时,RSpec 推荐使用 eq 而不是 ==。

    2,测试类方法和作用域

    #spec/models/contact_spec.rb
    def self.by_letter(letter)
        where("lastname LIKE ?", "#{letter}%").order(:lastname)
    end
    require 'spec_helper'
    describe Contact do
      # earlier validation examples omitted ...
      it "returns a sorted array of results that match" do
        smith = Contact.create(firstname: 'John', lastname: 'Smith',
                               email: 'jsmith@example.com'),
            jones = Contact.create(firstname: 'Tim', lastname: 'Jones',
                                   email: 'tjones@example.com'),
            johnson = Contact.create(firstname: 'John', lastname: 'Johnson',
                                     email: 'jjohnson@example.com')
        expect(Contact.by_letter("J")).to eq [johnson, jones]
      end
    end

    使用下面代码来检测返回值中是否没有包含联系人 smith

    expect(Contact.by_letter("J")).to_not include smith

     3,捕获异常

    expect {
            result = UI::ApplinkSqlBackup.get_sql_server_info(header, input)
          }.to raise_error(Esfbase::EsfStandardError)
    

      将可能发生异常的代码写在expect中,期待返回Esfbase::EsfStandardError类型的error

  • 相关阅读:
    Ubuntu 16.04 安装 Apache, MySQL, PHP7
    Ubuntu下apache2启动、停止、重启、配置
    织梦-数据库-表和字段说明手册
    DEDECMS去除后门隐患和漏洞以及冗余代码的方法
    Express使用html模板
    windows系统 安装MongoDB
    linux搭建node.js环境
    配置vuejs加载模拟数据
    安卓高级5 zXing
    安卓高级5 传感器和震动 模仿微信摇一摇Ui效果
  • 原文地址:https://www.cnblogs.com/fanxiaopeng/p/3577066.html
Copyright © 2011-2022 走看看