rspec test GET #index - 包含预期的集合

时间:2016-10-31 19:56:00

标签: ruby-on-rails ruby rspec

我测试。,索引操作'填充所有问题的数组。

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 

控制器/ questions_controller

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

工厂/ questions.rb

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

运行测试时显示错误:

1)QuestionsController GET #index填充所有问题的数组      失败/错误:期望(分配(:问题))。到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)>'

为什么不是集合的相同元素?

1 个答案:

答案 0 :(得分:1)

你需要在db中创建问题吗?如果您正在测试@questions是否已填充,则可以存根这些数据库调用,例如

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

如果您只想测试作业,则无需创建实际的db记录。