【发布时间】:2019-08-19 20:24:29
【问题描述】:
我的代码功能正常,但需要创建一个涵盖它的 RSpec 测试。 我的路线.rb:
resources :movies do
#member routes for individual ones
get 'find_with_same_director', on: :member
end
# map '/' to be a redirect to '/movies'
root :to => 'movies#index'
我在 movies_controller.rb 中的代码:
def find_with_same_director
@movie = Movie.find(params[:id])
@movies, check_info = Movie.find_with_same_director(params[:id])
if check_info
flash[:notice] = "'#{@movie.title}' has no director info"
redirect_to movies_path
end
end
模型movie.rb中的find_with_same_director函数:
def self.find_with_same_director(id)
movie = self.find(id)
if !movie.director.blank?
movies = self.where(:director => movie.director).where.not(:id => movie.id)
return movies, false
else
return [], true
end
end
我正在尝试编写测试,涵盖单击调用该函数的“查找同一导演”链接,当点击的电影有导演要显示,什么时候没有。到目前为止,我已经在 movies_controller_spec.rb 中为每个测试编写了以下测试:
describe 'find_with_same_director' do
it 'should call the find_with_same_director model method' do
expect(Movie).to receive(:find_with_same_director).with(params[:id])
get :find_with_same_director, id: movie.id
end
context 'movie has a director' do
let!(:movie1) {FactoryGirl.create(:movie, :director => movie.director)}
it do
get :find_with_same_director, id: movie1.id
expect(response).to redirect_to(movie_path(movie1.id))
end
end
context 'movie has no director' do
movie1 = FactoryGirl.create(:movie, :director => nil)
it "should redirect to root" do
get :find_with_same_director, id: movie1.id
expect(response).to redirect_to(/movies)
end
end
end
我在这些测试上花费了数小时,当我检查报告时它们“覆盖”了这些行,前两个返回失败。这意味着我写错了。我想修改这些测试以准确地表示我的控制器代码正在做什么,我非常感谢一些帮助。如果您对此感到满意,如果您也提供有关为模型 movie.rb 文件编写 rspec 测试代码的建议,我也将不胜感激。
我隔离第一个测试时遇到的错误:
1) MoviesController find_with_same_director should call the find_with_same_director model method
Failure/Error: expect(Movie).to receive(:find_with_same_director).with(params[:id])
NameError:
undefined local variable or method `params' for #<RSpec::ExampleGroups::MoviesController::FindWithSameDirector:0x000000056b27e0>
我隔离第二个测试时遇到的错误:
Failures:
1) MoviesController find_with_same_director movie has a director should redirect to "/movies/28"
Failure/Error: expect(response).to redirect_to(movie_path(movie2.id))
Expected response to be a <redirect>, but was <200>
我有点理解为什么会发生错误,只是不知道如何解决它们。
【问题讨论】:
-
在电影模型中,第三个代码sn-p,我在上面展示了那个代码。我也刚刚发布了我收到的错误。
-
如你所见,我在控制器中也有一个同名的控制器方法。这就是我在控制器测试中测试的内容
-
怎么样?我正在检查被点击的电影是否有导演。如果是,我完成任务,否则我为错误返回 true..
-
idk 告诉你什么,我是 MVC 和 ruby 以及 ruby on rails 的新手。只是想弄清楚这一点。我不认为这是导致问题的原因。我的重定向测试出了点问题。可能是 routes.rb?还是我的功能文件夹中的 path.rb?这就是为什么我在这里试图弄清楚
-
当我点击一部电影时,页面变为 /movies/movie.id,然后当我点击“查找同一导演的电影”时,页面变为 /movies/movie.id/find_with_same_director。我只需要在测试中描述它。 @lacostenycoder
标签: ruby-on-rails ruby ruby-on-rails-3 rspec rspec-rails