RSpec - 主题
RSpec 的优势之一是它提供了多种编写测试、干净测试的方法。当您的测试简短且整洁时,您可以更轻松地关注预期Behave,而不是关注测试编写方式的细节。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 的主题功能来减少示例中的代码量。我们通过将 person 对象实例化移动到描述行来做到这一点。
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 块,这最终需要更少的代码并且同样清晰。