2016-10-31 37 views
0

我测试。,该索引操作'填充所有问题的数组。rspec测试GET #index - 包含的预期集合

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

你需要在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 

,如果你只是想测试分配你并不需要创建实际的数据库记录。

+0

你能解释一下,什么做到这一点代码:@questions = [FactoryGirl.build_stubbed(:问题) 允许(问题)。为了接收(:所有).and_return(@questions) –

+0

肯定的是,'FactoryGirl.build_stubbed'将创建一个ActiveRecord对象(及其所有属性)而不写入数据库。 'allow(...)。'接收'调用被用来模拟(在这种情况下)对数据库的调用,所以,这就是说:好吧,当'Question.all'获得调用时,返回'@ questions'。 ..因为你没有在这里测试模型,所以你可以模拟数据库调用,事实上,如果你编写一个集成测试来执行整个堆栈 –

+0

谢谢,你根本不需要控制器测试。好的 –