Search code examples
ruby-on-railsrubyruby-on-rails-4rspecrspec-rails

Test service Rspec always return empty array


My service work perfectly testing manually, but I need write service test. So I create service test in rspec

require 'rails_helper'

RSpec.describe ReadService do
  describe '#read' do
    context 'with 4 count' do
      let!(:object1) { create(:obj) }
      let!(:object2) { create(:obj) }
      let!(:object3) { create(:obj) }
      let!(:object4) { create(:obj) }

      it 'return 2 oldest obj' do
        expect(ReadService::read(2)).to eq [report4,report3]
      end
    end

But ReadService::read(2) in test return []

When I type this manually

ReadService::read(2)

it return array with two oldest obj correctly. What do I wrong? I call this service in test not correctly ?

ReadService implementation

class ReadService
  def self.read(count)
    objects = Object.get_oldest(count)

    objects.to_a
  end
end

Solution

  • This happens because you use let!. This helper will only create the object when you first reference it, which you never do in your test. In this case you should rather use a before :each or before :all block (depending on what your specs do in the describe block):

    before :each do
      @object1 = create :obj
      @object2 = create :obj
      @object3 = create :obj
      @object4 = create :obj
    end
    

    If you do not need a reference to the objects, you can create them in a loop:

    4.times { create :obj }