Stefan Hansch Stefan Hansch - 1 month ago 13
Ruby Question

rspec test GET #index - expected collection contained

I test., that index action 'populates an array of all questions.

require 'rails_helper'

RSpec.describe QuestionsController, type: :controller do
describe 'GET #index' do
before do
@questions = FactoryGirl.create_list(:question, 2)
get :index
end

it 'populates an array of all questions' do
binding.pry
expect(assigns(:questions)).to match_array(@questions)
end
it 'renders index view' do
expect(response).to render_template(:index)
end
end
end


controllers/questions_controller

class QuestionsController < ApplicationController
def index
@questions = Question.all
end
end


factories/questions.rb

FactoryGirl.define do
factory :question do
title "MyString"
body "MyText"
end
end


When running tests display error:

1) QuestionsController GET #index populates an array of all questions
Failure/Error: expect(assigns(:questions)).to match_array(@questions)

expected collection contained:

[#<Question id: 37, title: "MyString", body: "MyText", created_at: "2016-10-31 19:37:12", updated_at:...: "MyString", body: "MyText", created_at: "2016-10-31 19:37:12", updated_at: "2016-10-31 19:37:12">]
actual collection contained: [#<Question id: 15, title: "MyString", body: "MyText", created_at: "2016-10-30 21:23:52", updated_at:...: "MyString", body: "MyText", created_at: "2016-10-31 19:37:12", updated_at: "2016-10-31 19:37:12">]
the extra elements were: [#<Question id: 15, title: "MyString", body: "MyText", created_at: "2016-10-30 21:23:52", updated_at:...: "MyString", body: "MyText", created_at: "2016-10-30 21:23:52", updated_at: "2016-10-30 21:23:52">]
# ./spec/controllers/questions_controller_spec.rb:12:in `block (3 levels) in <top (required)>'


Why not the same elements of the collection?

Answer

do you need to create questions in db? if you're testing that @questions is getting populated, you can stub those db calls, something like

describe 'GET #index' do
  before do
    @questions = [FactoryGirl.build_stubbed(:question)]
    allow(Question).to receive(:all).and_return(@questions)
    get :index
  end  

  it 'populates an array of all questions' do
    expect(assigns(:questions)).to match_array(@questions)  
  end
end

You don't need to create actual db records if you just want to test the assignment.

Comments