RSpec – 主题
RSpec – 主题
RSpec 的优势之一是它提供了许多编写测试、清理测试的方法。当您的测试简短而整洁时,更容易关注预期的行为,而不是关注如何编写测试的细节。RSpec Subjects 是另一种快捷方式,允许您编写简单明了的测试。
考虑这个代码 –
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 块替换为两个it 块,这最终需要更少的代码并且同样清晰。