- RSpec 教程
- RSpec——主页
- RSpec——引言
- RSpec——基本语法
- RSpec——编写规范
- RSpec——匹配器
- RSpec——测试替身
- RSpec——存根
- RSpec——钩子
- RSpec——标记
- RSpec——对象
- RSpec——辅助方法
- RSpec——元数据
- RSpec——筛选
- RSpec——预期
- RSpec 资源
- RSpec——快速指南
- RSpec——有用资源
- RSpec——讨论
RSpec——对象
RSpec 的一项优势在于它提供了多种编写测试的方法,编写清晰的测试。当测试简短且有条理时,就不必关注测试如何编写的细节,而可以轻松专注于预期行为。RSpec 对象是另一种捷径,可让你编写简单明了的测试。
考虑此代码 −
class Person
attr_reader :first_name, :last_name
def initialize(first_name, last_name)
@first_name = first_name
@last_name = last_name
end
end
describe Person do
it 'create a new person with a first and last name' do
person = Person.new 'John', 'Smith'
expect(person).to have_attributes(first_name: 'John')
expect(person).to have_attributes(last_name: 'Smith')
end
end
它实际上相当清晰,但我们可以使用 RSpec 的 subject 特性来减少示例中的代码量。为此,我们将 person 对象实例化移至 describe 行中。
class Person
attr_reader :first_name, :last_name
def initialize(first_name, last_name)
@first_name = first_name
@last_name = last_name
end
end
describe Person.new 'John', 'Smith' do
it { is_expected.to have_attributes(first_name: 'John') }
it { is_expected.to have_attributes(last_name: 'Smith') }
end
运行此代码时,你会看到以下输出 −
.. Finished in 0.003 seconds (files took 0.11201 seconds to load) 2 examples, 0 failures
请注意,第二个代码示例要简单得多。我们获取第一个示例中的一个it 块,并用两个it 块取代该块,最终所需的代码更少,并且一样清晰。
广告