【问题标题】:index rspec test failing索引 rspec 测试失败
【发布时间】: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


【解决方案1】:

解决了!必须这样做:

require 'rails_helper'

RSpec.describe MyGamesResultsController, type: :controller do
  describe "GET index" do

   let!(:user) { create(:user) }
   let!(:contest) { create(:contest) }
   let!(:my_entry) { create(:entry, user_id: user.id, contest_id: contest.id) }


   before :each do
     sign_in user
     get :index, contest_id: contest.id
   end

   it "renders the index template" do
    (expect (response.status)).to eql(200) 
   end
 end
end

【讨论】:

    猜你喜欢
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多