rspec_rails_4 icon indicating copy to clipboard operation
rspec_rails_4 copied to clipboard

Ch.5, p.53 - Unnecessary assign & order of creates in spec

Open olerass opened this issue 11 years ago • 0 comments

In the test populates an array of contacts starting with the letter on page 53, the Jones contact is assigned to an unused jones variable:

it "populates an array of contacts starting with the letter" do
  smith = create(:contact, lastname: 'Smith')
  jones = create(:contact, lastname: 'Jones')
  get :index, letter: 'S'
  expect(assigns(:contacts)).to match_array([smith])
end

The assignment is unnecessary.

Furthermore, I suggest reversing the order of the creates. As it is now the test would pass if the production code always returns a one-element array with the first contact in the database (a plausible mistake), because the test first creates smith and then tests that [smith] is returned. Instead, by first creating jones and checking that [smith] is returned, you require the production code to at least do something intelligent because it needs to pass over jones and only return smith.

To be honest an even better test would create four contacts and check that the two in the middle are returned. That would cover more edge cases than the current one and be more representative of the desired behavior.

Book version: 2013-10-29 (PDF)

olerass avatar Nov 02 '13 13:11 olerass