简单的测试文件
测试文件model:
require 'rails_helper'
describe Model_Name do
it 'is .....' do
//test code
end
end
*** 在每个测试文件的开头是:require 'rails_helper'
***
Rspec新句法
// 方式1
it 'adds 2 and 1 to make 3' do
(2 + 1).should eq 3
end
//方式2
it 'adds 2 and 1 to make 3' do
expect(2+1).to eq 3
end
现在鼓励使用下面这种方式,尽量少使用should
语法。
第一个测试
it 'is valid with a firstname, lastname and email' do
contract = Contact.new(
firstname: 'Fugang',
lastname: 'Cui',
email:
);
expect(contract).to be_valid
end
这里我们创建了一个contact
对象,并调用rspec
的be_valid
匹配器验证其合法性。
测试实例方法
我们在Contact
中有一个name
方法
def name
[firstname, lastname].join(' ')
end
下面我们将为这个实例方法写单元测试。
it 'return a contact full name as a string' do
contact = Contact.new(
firstname: 'Fugang',
lastname: 'Cui',
email:
)
expect(contact.name).to eq 'Fugang Cui'
end
测试类方法和作用域
我们测试Contact
类中by_letter
方法
def self.by_letter(letter)
where("lastname LIKE ?", "#{letter}%").order(:lastname)
end
测试代码
it 'returns a sorted array of results that match' do
su = Contact.create(
firstname: 'Kai',
lastname: 'Su',
email:
)
zhou = Contact.create(
firstname: 'Xing',
lastname: 'Zhou',
email:
)
zhi = Contact.create(
firstname: 'Kai',
lastname: 'Zhi',
email:
)
expect(Contact.by_letter("zh")).to eq [zhi, zhou]
expect(Contact.by_letter("zh")).not_to include su
end