对于我的Rails 4应用程序,我想测试删除一个Course对象会删除关联的Chapter对象。
在我的课程模型中,我将联盟定义如下:
has_many :chapters, dependent: :delete_all
这很好用。但是,我无法弄清楚如何为此级联删除编写测试。
我的Rspec测试看起来像这样:
before do
@course = Fabricate(:course)
end
it "deletes associated chapters" do
set_current_admin
chapter1 = Fabricate(:chapter, course_id: @course_id)
delete :destroy, id: @course.id
expect(Chapter.count).to eq(0)
end
我希望Chapter.all为0,但是当我运行此测试时,我得到了这个结果:
1) Admin::CoursesController DELETE #destroy deletes associated chapters
Failure/Error: expect(Chapter.all).to eq(0)
expected: 0
got: #<ActiveRecord::Relation [#<Chapter id: 709, title: "omnis corrupti eos et aperiam", description: "Alias sunt tempore aut deserunt. Optio ea assumenda...", course_id: nil, created_at: "2013-11-01 07:10:28", updated_at: "2013-11-01 07:10:28", tagline: "Omnis nemo praesentium corporis. Doloremque dolorib...", badge_image: nil>]>
(compared using ==)
# ./spec/controllers/admin/courses_controller_spec.rb:181:in `block (3 levels) in <top (required)>'
如何让这个测试通过?
感谢您的帮助,
安东尼
答案 0 :(得分:0)
Chapter.all
是ActiveRecord :: Relation(Rails 4)的一种方法,它不返回数字。
您想测试计数,请使用Chapter.count
答案 1 :(得分:0)
这不是RSpec,但以下内容可能会提供一些动力。
test 'authentication - dependent destroy' do
user = users(:adam)
authentication = user.authentications.first
user.destroy
assert_nil Authentication.find_by_id(authentication.id)
end