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的主题功能来减少示例中的代码量.我们通过将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 block 并用两个 it blocks 替换它,这最终需要更少的代码并且同样清晰.