jeudi 19 juillet 2018

Rspec inconsistent results between 2 tests with same code

I have a model spec that throws an unexpected error (doesn't build the object right). When I move the same code into a previous test, it runs smoothly.

Here's the problematic expectation:

expect(title.full_title.length).to be <= 140

When adding the line to the first test, it passes, while the second test fails:

  describe "generates a title" do
    let(:collection) { FactoryBot.create(:collection) }
    let(:items) { FactoryBot.create_list(:item, 10, collection: collection, chosen: true) }
    let(:title) { Title.create_title(collection) }

context "happy path" do
  it "assigns keywords by score" do
    array = []
    items.each do |i|
      array << [i.search.term, i.search.score]
    end
    array.sort! { |a, b| a[1] <=> b[1] }
    split_title = title.full_title.split(', ')
    remaining_chars = 140
    i = 0

    split_title.each do |s|
      if remaining_chars - s.length >= 0
        expect(s).to eq(array[i][0])
        i +=  1
        remaining_chars -= s.length
      end

      expect(title.full_title.length).to be <= 140
    end
  end

  it "does not exceed 140 characters" do
    expect(title.full_title.length).to be <= 140
  end
end

Here is the error message, it doesn't create the object:

  1) Title generates a title sad path does not repeat keywords
     Failure/Error: remaining_chars = 140 - keywords[0].length

     NoMethodError:
       undefined method `length' for nil:NilClass

TIA!

Aucun commentaire:

Enregistrer un commentaire