【发布时间】:2015-09-10 20:01:33
【问题描述】:
我在为试图测试的控制器的索引操作编写规范时遇到困难。控制器如下所示:
class MyGamesResultsController < ApplicationController
def index
@contest = Contest.find(params[:contest_id])
@my_entry = current_user.entries.where(contest_id: params[:contest_id])
@points_per_player = @my_entry[0].points_per_player
@total_points = @my_entry[0].total_points
end
end
我的规范看起来像这样:
require 'rails_helper'
RSpec.describe MyGamesResultsController, type: :controller do
describe 'GET /index' do
let!(:user) { create(:user) }
before :each do
sign_in user
get :index
end
it 'renders the index template' do
expect(subject).to render_template(:index)
end
end
end
规范返回的错误是这样的:
失败/错误:获取 :index ActiveRecord::RecordNotFound: 找不到“id”= 的比赛
谁能找出问题所在?
【问题讨论】:
-
您的测试模拟了对
/index的GET 请求,但在您的控制器中,您使用params[:contest_id]来查找竞赛记录。你确定这个contest_id是在你的测试中的参数哈希中给出的吗? -
我认为我的测试中的 params 哈希中没有给出比赛 ID。我怎么做?对不起,我应该提到我是 Rails 新手
-
我觉得就这么简单:
get :index, contest_id: some_id(其中变量some_id包含一个实际的竞赛ID,在调用get之前可以找到) -
有没有办法模拟这个或什么?
-
一个非常直接的方式来做到这一点:
get :index, contest_id: Contest.first.id
标签: ruby-on-rails rspec bdd