我是Rails和Rspec的新手,我正在使用Rspec来测试这个控制器方法,其中包括异常处理:
def search_movies_director @current_movie = Movie.find(params[:id]) begin @movies = Movie.find_movies_director(params[:id]) rescue Movie::NoDirectorError flash[:warning] = "#{@current_movie} has no director info" redirect_to movies_path end end
我无法弄清楚如何正确测试所述路径:无效搜索(收到错误后)应该重定向到主页.我试过这样的东西:
describe MoviesController do describe 'Finding Movies With Same Director' do #some other code context 'after invalid search' do it 'should redirect to the homepage' do Movie.stub(:find) Movie.stub(:find_movies_director).and_raise(Movie::NoDirectorError) get :search_movies_director,{:id => '1'} response.should redirect_to movies_path end end end end
运行测试失败并出现错误:NameError:未初始化的常量Movie :: NoDirectorError
谢谢!
更新:
正如nzifnab所说,它找不到Movie :: NoDirectorError.我忘了定义这个异常类.所以我把它添加到app / models / movie.rb中:
class Movie < ActiveRecord::Base class Movie::NoDirectorError < StandardError ; end #some model methods end
这解决了我的问题,这个测试通过了.