shoulda-matchers--Ruby单元测试小帮手

详细文档大家可以点击github的官方说明,不过是英文版本哦     

https://github.com/thoughtbot/shoulda-matchers

shoulda-matchers provides Test::Unit- and RSpec-compatible one-liners that test common Rails functionality. These tests would otherwise be much longer, more complex, and error-prone.

 shoulda-matchers对应了可以测试Rails常规功能的方法,使得测试用例非常简洁高效

如何安装使用?

   (1)把下面的几行加到Gemfile文件里

group :test do
  gem 'shoulda-matchers', require: false 
end

其中require:false表示不自动加载

(2)修改spec_helper.rb,加上下面两行
require 'rspec/rails'
require 'shoulda/matchers'

下面来看一下匹配的内容

ActiveModel Matchers

ActiveRecord Matchers

ActionController Matchers

 重头戏就是下面的例子啦

# -*- encoding : utf-8 -*-
class CmsUser < ActiveRecord::Base
  validates_presence_of :email
  validates_uniqueness_of :email

  def password=(password)
    write_attribute :password, self.class.md5(password)
  end

  def self.authenticate(username, password)
    CmsUser.where(username: username, password: md5(password)).first
  end

  def self.md5(str)
    Digest::MD5.hexdigest(str.to_s)
  end
end

看下对应的cms_user_spec.rb测试

# -*- encoding : utf-8 -*-
require 'spec_helper'
describe CmsUser do
  describe "validations" do
    it { should validate_presence_of(:email) }
    it { should validate_uniqueness_of(:email) }

    it "valid" do
      user = build :cms_user
      user.should be_valid
    end
  end

  describe "set password" do
    it "value will convert to md5" do
      user = build :cms_user
      user.password = "password"
      user.password.should eq Digest::MD5.hexdigest("password")
    end
  end
  describe "authenticate with username and password" do
    let!(:tester) { create :cms_user, username: "user", password: "password" }

    it "return user with valid user info" do
      user = CmsUser.authenticate tester.username, "password"
      user.id.should eq tester.id
    end

    it "return nil with invalid user info" do
      user = CmsUser.authenticate tester.username, "wrong_password"
      user.should be_nil
    end
  end
end

 

转载于:https://www.cnblogs.com/iwangzheng/p/4029617.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值