我想添加一项功能,通过单击一个按钮返回属于一个导演的所有电影信息。它已经实现并且运行良好,但在编写Rspec测试时出现了一些错误。错误消息是:
(1)MoviesController searching for movies by the same director when 'Director' info exists should post @director and @movies variables for view
Failure/Error: get :find_movies_by_same_director, :movie_id => @movie.id, :movie_director => @movie.director
ActionController::RoutingError:
No route matches {:movie_id=>"1", :movie_director=>["Star Wars", "THX-1138"], :controller=>"movies", :action=>"find_movies_by_same_director"}
# ./spec/controllers/movie_controller_spec.rb:15:in `block (4 levels) in <top (required)>'
以下测试中发现没有找到路由的类似错误,所以我认为我的路由文件可能存在一些问题。这是我在routes.rb中指定的路径:
get '/movies/:id/director', to: 'movies#find_movies_by_same_director', as: 'director'
Rspec文件是:
require "spec_helper"
describe MoviesController do
it { should respond_to(:find_movies_by_same_director) }
describe "searching for movies by the same director" do
context "when 'Director' info exists" do
before do
@movie = double(:title => "Star Wars", :id => "1", :director => "George Lucas")
Movie.stub(:find).with("1").and_return @movie
@lucas_films = ["Star Wars", "THX-1138"]
@movie.stub(:director).and_return @lucas_films
end
it "should post @director and @movies variables for view" do
get :find_movies_by_same_director, :movie_id => @movie.id
assigns(:director).should == @movie.director
assigns(:movies).should == @lucas_films
end
end
end
控制器方法是:
def find_movies_by_same_director
@movie = Movie.find(params[:id])
@director = @movie.director
if (not @director.nil?) and (not @director.empty?)
@movies = Movie.where(director: @director) if (not @director.nil?) and (not @director.empty?);
#@movies = Movie.find_by_sql("SELECT * FROM movies i WHERE i.director == '#{@director}'")
render :director
else
flash[:notice] = "'#{@movie.title}' has no director info"
redirect_to root_path
end
我刚刚开始学习Rspec,所以任何评论或建议都会受到赞赏。
答案 0 :(得分:1)
从路径中可以看出,您的操作需要参数:id
。您正在通过:movie_id
。所以,只需在规范中替换此行
get :find_movies_by_same_director, :movie_id => @movie.id
与
get :find_movies_by_same_director, :id => @movie.id
再试一次。