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)>'
为什么不是集合中的相同元素?
你能解释一下,什么做到这一点代码:@questions = [FactoryGirl.build_stubbed(:问题) 允许(问题)。为了接收(:所有).and_return(@questions) –
肯定的是,'FactoryGirl.build_stubbed'将创建一个ActiveRecord对象(及其所有属性)而不写入数据库。 'allow(...)。'接收'调用被用来模拟(在这种情况下)对数据库的调用,所以,这就是说:好吧,当'Question.all'获得调用时,返回'@ questions'。 ..因为你没有在这里测试模型,所以你可以模拟数据库调用,事实上,如果你编写一个集成测试来执行整个堆栈 –
谢谢,你根本不需要控制器测试。好的 –