I have in project.rb:
has_many :items, :dependent => :destroy
And in item.rb:
belongs_to :project
My projects fixture:
b1_s_first_project:
title: B1's first project
And my items fixture:
b1_s_first_project_s_first_item:
title: B1's first project's first item
project: b1_s_first_project
In my unit test, I set local variables item = items(:b1_s_first_project_s_first_item)
and project = projects(:b1_s_first_project)
. When I call p开发者_开发技巧roject.destroy
, project.destroyed?
returns true, but item.destroyed?
returns nil, as if it hadn't been destroyed. What am I missing? Thanks in advance.
It looks like you might need to add item.reload
before testing if it's destroyed or not
Just to provide an alternative method by leveraging .reload
on the association record using the assertion assert_raise
. This works under Rails 5, but should work in the the previous two versions.
Model set-up:
# foo.rb
class Foo < ApplicationRecord
has_many :bars, dependent: :destroy
end
# bar.rb
class Bar < ApplicationRecord
belongs_to :foo
end
Fixture set-up:
# foos.yml
oof:
title: Hello
# bars.yml
rab:
title: World!
foo: oof
Model minitest:
test 'foo should destroy dependency bar on destroy' do
foo, bar = foos(:off), bars(:rab)
assert foo.destroy
assert_raise(ActiveRecord::RecordNotFound) { bar.reload }
end
精彩评论