简体   繁体   中英

Rspec test got: nil

I'm trying to do a basic rspec test, which looks like this;

require 'rails_helper'

  describe ReviewsController do

  describe "GET #index" do
   it "assigns a new review to @reviews" do
   review = Review.create( rating: 4 )

   get :index

   expect(assigns(:review)).to eq([review])
   assert_response :success
  end
 end
end

But I'm getting the failure: expected: Review id: 8, rating: 4, created_at: "2016-07-19 11:58:28", updated_at: "2016-07-19 11:58:28", user_id: nil, game_id: nil got: nil

My ReviewsController looks like this:

class ReviewsController < ApplicationController

  def index
   @reviews = Review.all
  end

  def show
   @review = Review.find(params[:rating])
  end

  def create
   review = Review.new(review_params)

   respond_to do |format|
   if @review.save
    format.html { redirect_to root_url, notice: 'Review was successfully updated.' }
    format.json { render :show, status: :ok, location: @review }
  else
    format.html { render :new }
    format.json { render json: @review.errors, status: :unprocessable_entity }
   end
  end
 end

  private

  def post_params
   params.require(:post).permit(:message)
  end
 end

In case you need it, here's the review model:

class Review < ActiveRecord::Base
 belongs_to :user
 belongs_to :game
 validates_presence_of :rating

 validates_uniqueness_of :user_id
end

I don't understand why it's asking for a user_id or game_id, because it's only about the reviews..

You have to change the below

expect(assigns(:review)).to eq([review])

to

expect(assigns(:reviews)).to eq([review])

The reason is @reviews is the instance variable you have inside the #index controller action, not @review .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM