Consider this code −
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 endIt’s actually pretty clear as is, but we could use RSpec’s subject feature to reduce the amount of code in the example. We do that by moving the person object instantiation into the describe line.
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') } endWhen you run this code, you will see this output −
.. Finished in 0.003 seconds (files took 0.11201 seconds to load) 2 examples, 0 failuresNote, how much simpler the second code sample is. We took the one it block in the first example and replaced it with two it blocks which end up requiring less code and are just as clear.
No comments:
Post a Comment