2013-11-01 32 views
0

爲我的Rails 4應用測試級聯刪除,我想測試刪除Course對象是否刪除關聯的章節對象。如何使用Rspec

在那裏,我的課程模型我定義的assiociation如下:

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

Chapter.all是的ActiveRecord的方法::關係(軌道4),它不返回一個數字。

你想測試的數量,使得使用Chapter.count

+0

我在回答 – gotva

+0

上增加了一些解釋感謝幫助gotva。我現在使用Chapter.count,但我的測試仍然失敗,說它得到0,但檢查1 – Toontje

+0

你可以更新你的代碼在 – gotva

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