美文网首页
rails-rspec

rails-rspec

作者: GALAXY_ZMY | 来源:发表于2019-01-07 21:43 被阅读23次
一、为什么需要测试:

测试对于程序来说,不是必不必要的问题,而是怎么测的问题。就算不写测试,你一样在人肉测试。只不过人肉测试效率太低,出错率也高,对于中等和以上规模的程序,需要写测试来代替人肉测试,以减轻工作强度罢了。

功能和代码不断的扩充,不断重构和优化,这个过程中,没有好的测试,基本就掉入修bug泥潭了。有话说改一个bug带来3个bug,自动测试一定程度上可以减轻这个状况。总之,逻辑简单,或者写完没有更改的必要,类似这种代码人肉测测也无可厚非,逻辑稍微复杂的,以后更改的可能性存在的, 那么自动测试毫无疑问是必要的。

二、安装

在Gemfile配置文件中,配置如下信息

group :test do
  gem 'rspec-rails', '~> 3.7'
end

执行bundle install来安装这个gem,此gem依赖gem rspec,所以不用单独安装rspec。
然后执行 rails generate rspec:install生成rspec相关文件,会生成以下三个文件

.rspec
spec/spec_helper.rb
spec/rails_helper.rb

运行rspec命令执行测试
bundle exec rspecbundle exec rake spec
此命令会执行spec文件夹下的所有以_spec.rb结尾的文件。

三、示例

下面是要测试的model文件

# models/app/user.rb
class App::User < ApplicationRecord
    def is_employee?
      self.app_user_type.to_i == 21
    end
end

我们要测试user.rb文件下的实例方法is_employee?,这个方法可能返回两个值truefalse,所以我们的测试要分两种情况

#spec/models/app/user_spec.rb
require "rails_helper"
RSpec.describe App::User, :type => :model do
  describe '#is_employee?' do
    context "when app_user is employee" do
      it "should respond with true" do
        app_user = App::User.create!(true_name: '王先生', mobile: '13700000000', app_user_type: 1)
        expect(app_user.is_employee?).to eq(false)
      end
    end
    context "when app_user is not employee" do
      it "should respond with false" do
        app_user = App::User.create!(true_name: '王先生', mobile: '13700000000', app_user_type: 21)
        expect(app_user.is_employee?).to eq(true)
      end
    end
  end
end

(注释:通常,我们使用describe来描述方法。遵循ruby注释规范,在方法名前使用点号‘.’或‘::’表示测试的是类方法,用“#”表示测试的是实例方法)

然后在控制台执行bundle exec rspec(或者只执行某个文件rspec spec/models/app/user_spec.rb),在控制台会看到下面的内容:

表示执行成功两段测试,0个失败

如果失败了是什么情况呢?我们把第一段的eq(false)改成eq(true)看一下运行结果:

错误信息一目了然
四、数据准备方法let

如果再添加user的其他实例方法,我需要在新的测试例子中再创建一个app_user实例,再测试的例子越来越多时会发现数据准备占了大部分的代码量。

# 这一段:
let(:app_user) { App::User.new }

# 基本上和这一段完全等同
def app_user
  @app_user ||= App::User.new
end

这时我们就需要用到let方法,如下:

#spec/models/app/user_spec.rb
require "rails_helper"
RSpec.describe App::User, :type => :model do
  describe '#is_employee?' do
    let(:app_user) {App::User.create!(true_name: '王先生', mobile: '13700000000', app_user_type: 1)}
    let (:employee_user) {App::User.create!(true_name: '王先生', mobile: '13700000000', app_user_type: 21)}
    context "when app_user is employee"
        ...
    context "when app_user is not employee"
        ...
  end
end

其实还有一个方法before,可以这样写(但我们通常不用before)

describe '#is_employee?' do
   before { @app_user = App::User.create :app_user_type, :mobile, :true_name}
   it "should respond with false" do
        expect(@app_user.is_employee?).to eq(true)
   end
end

当需要给一个变量赋值时,使用 let 而不是before来创建这个实例变量。let采用了 lazy load 的机制,只有在第一次用到的时候才会加载,然后就被缓存,直到测试结束。

before(:each)会自动初始化变量。如果其中的某一个测试用力不需要这些变量,依然需要初始化,如初始化变量需要很多时间,对这个测试的初始化会浪费多余的时间和资源.

五、factory_bot

一个让数据准备更方便的工具

rails下安装:gem "factory_bot_rails"

配置,在config/environments/test.rb下配置如下内容:

RSpec.configure do |config|
  config.include FactoryBot::Syntax::Methods
end

在spec下创建一个factories文件夹,在这个文件夹下做FactoryBot数据相关的配置

比如上面提到的App::User的配置:

FactoryBot.define do
  # employee账号
  factory :employee_user, class: 'App::User' do
    id 10360
    app_user_type 21
    true_name '吴先生'
    mobile 13700000000
  end
  # 非employee账号
  factory :app_user, class: 'App::User' do
    id 10361
    app_user_type 3
    true_name '王先生'
    mobile 13700000000
  end
end

然后我们的测试就可以这样写:

describe '#is_employee?' do
    let (:app_user) {build(:app_user)}
    let (:employee_user) {build(:employee_user)}
    context "when app_user is employee" do
      it "should respond with true" do
        expect(app_user.is_employee?).to eq(false)
      end
    end
    context "when app_user is not employee" do
      it "should respond with false" do
        expect(employee_user.is_employee?).to eq(true)
      end
    end
end

在FactoryBot定义时我们可以只定义一个app_user,employee_user可以这样生成:

let(:app_user) {  build(:app_user)  }
let(:employee_user) {  build(:app_user, app_user_type: 3)  }

build相当于App::User.new, FactoryBot还有create等其他方法,具体方法参考https://github.com/thoughtbot/factory_bot/blob/master/GETTING_STARTED.md

六、模拟方法--mock
# models/app/user.rb
def type_name
    self.is_employee? ? '高级账号' : '普通账号'
end

如果self.is_employee?判断很多,在测试type_name方法时我们不用过多的为is_employee?准备数据,我们应该只关注type_name方法的测试,这时候我们只需要这样:

  app_user.should_receive(:is_employee?).and_return(true)
  expect(app_user.type_name).to eq('高级账号')

通过mock方法,我们可以模拟某些值或方法,在上面的方法中,我们模拟方法is_employee?始终返回true。

FactoryGirl模拟真实的字段,mock可以模拟模型不存在的字段,mock可以用来虚拟比较复杂的属性或方法。

七、rspec断言

rspec 提供丰富多样的断言形式,满足我们的大部分需求,下面是其中一部分语法:

1、equal:
expect(actual).to be(expected) # passes if actual.equal?(expected)
expect(actual).to equal(expected) # passes if actual.equal?(expected)
expect(actual).not_to eq(expected) 

2、比较:
expect(actual).to be > expected
expect(actual).to be >= expected
expect(actual).to be <= expected
expect(actual).to be < expected
expect(actual).to be_within(delta).of(expected)

3、正则表示式:
expect(actual).to match(/expression/)
Note: The new expect syntax no longer supports the=~ matcher.

4、Types/classes:
expect(actual).to be_an_instance_of(expected) # passes if actual.class == expected
expect(actual).to be_a(expected) # passes if actual.is_a?(expected)
expect(actual).to be_an(expected) # an alias for be_a
expect(actual).to be_a_kind_of(expected) # another alias

5、真假匹配:
expect(actual).to be_truthy # passes if actual is truthy (not nil or false)
expect(actual).to be true # passes if actual == true
expect(actual).to be_falsy # passes if actual is falsy (nil or false)
expect(actual).to be false # passes if actual == false
expect(actual).to be_nil # passes if actual is nil
expect(actual).to_not be_nil # passes if actual is not nil

6、报错部分:
expect { ... }.to raise_error
expect { ... }.to raise_error(ErrorClass)
expect { ... }.to raise_error("message")
expect { ... }.to raise_error(ErrorClass, "message")

7、throws:
expect { ... }.to throw_symbol
expect { ... }.to throw_symbol(:symbol)
expect { ... }.to throw_symbol(:symbol, 'value')

8、谓词匹配器:
expect(actual).to be_xxx # passes if actual.xxx?expect(actual).to have_xxx(:arg) # passes if actual.has_xxx?(:arg)

9、集合:
expect(actual).to include(expected)
expect(actual).to start_with(expected)
expect(actual).to end_with(expected)
expect(actual).to contain_exactly(individual, items)# …which is the same as:expect(actual).to  match_array( expected_array ) 

例子:
expect([1, 2, 3]).to include(1)
expect([1, 2, 3]).to include(1, 2)
expect([1, 2, 3]).to start_with(1)
expect([1, 2, 3]).to start_with(1, 2)
expect([1, 2, 3]).to end_with(3)
expect([1, 2, 3]).to end_with(2, 3)
expect({:a => 'b'}).to include(:a => 'b')
expect("this string").to include("is str")
expect("this string").to start_with("this")
expect("this string").to end_with("ring")
expect([1, 2, 3]).to contain_exactly(2, 3, 1)
expect([1, 2, 3]).to match_array([3, 2, 1])
八、测试报告

执行下面的命令生成测试报错,生成的文件在项目根目录下
rspec --format html --out rspec_test.html
下面是测试报告的页面:

测试报告
九、结束语

看看这篇文章,理解为什么需要测试,对自己的代码负责!
https://chloerei.com/2015/10/26/testing-guide/

人非圣贤孰能无过,不同于 C/C++这类编译型语言,ruby作为解释型语言,有些语法性的错误有时较难发现,测试能为我们规避不少这类问题!

相关文章

  • rails-rspec

    一、为什么需要测试: 测试对于程序来说,不是必不必要的问题,而是怎么测的问题。就算不写测试,你一样在人肉测试。只不...

网友评论

      本文标题:rails-rspec

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