2014-07-10 13 views
10

Ứng dụng của tôi đang truyền một ActiveRecord :: RecordNotFound tới bộ điều khiển khi một mô hình không thể truy xuất bản ghi.Thử nghiệm cho ActiveRecord :: RecordNotFound

Dưới đây là truy vấn DB:

def self.select_intro_verse 
    offset = rand(IntroVerse.count) 
    IntroVerse.select('line_one', 'line_two', 'line_three', 'line_four', 'line_five').offset(offset).first!.as_json 
end 

first! đặt ra một ActiveRecord::RecordNotFound nếu không có hồ sơ được tìm thấy, và tôi có thể cứu nó và đưa ra một mẫu thích hợp trong điều khiển của tôi.

Đây là hành vi mong đợi vì vậy tôi muốn có một thử nghiệm cho nó trong thông số kỹ thuật của tôi. Tôi đã viết:

context "verses missing in database" do 
    it "raises an exception" do 
    expect(VerseSelector.select_intro_verse).to raise_exception 
    end 
end 

Khi tôi chạy rspec:

1) VerseSelector verses missing in database raises an exception Failure/Error: expect(VerseSelector.select_intro_verse).to raise_exception ActiveRecord::RecordNotFound: ActiveRecord::RecordNotFound

Đối với tôi những thử nghiệm thất bại mặc dù ngoại lệ xảy ra! Làm cách nào tôi có thể vượt qua bài kiểm tra?

Trả lời

22

Look in tài liệu cho rspec-expectations#expecting-errors này:

expect(VerseSelector.select_intro_verse).to raise_exception 

nên except cú pháp cho ngoại lệ phải lambda hoặc proc:

expect { VerseSelector.select_intro_verse }.to raise_exception(ActiveRecord::RecordNotFound) 
+0

+1 Thành thật mà nói. :-) –

+0

_must be lambda or proc_ - nên được in đậm :) – Fabio

Các vấn đề liên quan