Search code examples
ruby-on-rails-4rspec-railsrspec3

Rspec Change Matcher and factory girl


I'm using factory girl to create my objects. I'm wondering why I have to do the following:

RSpec.describe V1::SlotsController, type: :controller do
  let(:valid_slot) { create(:slot) }
  let(:valid_attributes) { attributes_for(:slot) }

  describe "DELETE destroy" do
    it "destroys the requested slot" do
      slot = Slot.create! valid_attributes # not working without this line
      expect {
        delete :destroy, { id: slot.id }
      }.to change(Slot, :count).by(-1)
    end
  end
end

If I do not overwrite slot, and just use the one created by factory_girl, the test will not pass. Why that?


Solution

  • because let is "lazy loaded". You should use

    let!(:slot) { create(:slot) }
    
    describe "DELETE destroy" do
      it "destroys the requested slot" do
        expect {
          delete :destroy, { id: slot.id }
        }.to change(Slot, :count).by(-1)
      end
    end