首页 > 其他 > 详细

rspec的一些常见用法

时间:2014-04-22 16:54:03      阅读:604      评论:0      收藏:0      [点我收藏+]

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

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

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

bubuko.com,布布扣
it "is true when true" do
    true.should be_true
end
#新用法
it "is true when true" do
    expect(true).to be_true
end

bubuko.com,布布扣

一,测试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
bubuko.com,布布扣
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
bubuko.com,布布扣

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

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

 

 3,捕获异常

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

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

rspec的一些常见用法,布布扣,bubuko.com

rspec的一些常见用法

原文:http://www.cnblogs.com/fanxiaopeng/p/3577066.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!