marimaf
marimaf

Reputation: 5410

rspec not destroying record and failing test

I'm in the process of upgrading a legacy project to rails 5.0 and some tests are failing. I have the following test:

describe ItemRun do
  describe "#item_template" do
    context "with an item template that has been deleted" do
      let(:item_template) { ItemTemplate.create! title: "Hello" }
      let!(:item_run) { item_template.item_runs.create! title: "Testing" }

      before do
        item_template.update_attributes(deleted: true)
      end

      it "responds to :title" do
        expect(item_run.item_template.title).to eq ""
      end
    end
  end
end

The error reports the following:

ItemRun#item_template with a item template that has been deleted responds to :title
     Failure/Error: expect(item_run.item_template.title).to eq ""

       expected: ""
            got: "Hello"

       (compared using ==)
     # ./spec/models/item_run_spec.rb:14:in `block (4 levels) in <top (required)>'

I also tried item_template.destroy but got the same result.

item_template.rb has the following class defined:

  class NullObject
    def title
      ""
    end
  end

Any ideas?

Upvotes: 1

Views: 504

Answers (1)

SteveTurczyn
SteveTurczyn

Reputation: 36880

destroy on an active record object will remove it from the database but the object remains in memory.

better would be to do a

item_run.reload

before the expect, but depending on how you defined the relationship you may then get an error that item_template is not found.

If your 'item_template' has

has_many :item_runs, dependent: :nullify

Then there won't be an error (assuming item_run has belongs_to :item_template, optional: true)

But as item_run will have no item_template then doing item_run.item_template.title will give you an error of no method on Nil:NilClass.

The underlying quetion is... should an item_run exist without an item_template ?

If not then do

has_many :item_runs, dependent: :destroy

And that will destroy the item_run automatically.

Upvotes: 1

Related Questions