我是RSpec的新手,我想知道为什么我没有通过这个测试
before(:each) { get :index }
it "assigns all favorites as @favorites" do
favorite = FactoryGirl.create(:favorite)
expect(assigns(:favorites)).to eq([favorite])
end
它说
1) FavoritesController GET index assigns all favorites as @favorites
Failure/Error: expect(assigns(:favorites)).to eq([favorite])
expected: [#<Favorite id: 1, patient_id: 6, doctor_id: 5>]
got: #<ActiveRecord::Relation []>
(compared using ==)
Diff:
@@ -1,2 +1,2
-[#<Favorite:0x000000058a5ca0 id: 1, patient_id: 6, doctor_id: 5>]
+[]
似乎assigns(:favorites)
空了。我也试过了另一种方法
def valid_attributes
doctor = FactoryGirl.create(:doctor)
patient = FactoryGirl.create(:patient)
FactoryGirl.attributes_for(:favorite, doctor_id: doctor.id, patient_id: patient.id)
end
it "assigns all favorites as @favorites" do
favorite = Favorite.create! valid_attributes
expect(assigns(:favorites)).to eq([favorite])
end
它也有同样的错误。任何输入对我都有帮助,我想询问是否有任何方法可以简化它。
更新
应用程序/控制器/ favorite_controller.rb
class FavoritesController < ApplicationController
before_action :set_favorite, only: [:destroy]
before_action :authenticate_user!
def index
@favorites = Favorite.where(:patient_id => current_user.id).order(id: :asc)
end
end
规格/控制器/ favorite_controller_spec.rb
require 'spec_helper'
describe FavoritesController, type: :controller do
login_patient
describe "GET index" do
let!(:favorite) { FactoryGirl.create(:favorite) }
before { get :index }
it { expect(response).to render_template(:index) }
it { expect(response).to be_success }
it { expect(response).to have_http_status(200) }
it "blocks unauthenticated access", :skip_before do
expect(response).to redirect_to(new_user_session_path)
end
it "assigns all favorites as @favorites" do
expect(assigns(:favorites).to_a).to eq([favorite])
end
end
end
规格/支持/ controller_helpers.rb
module ControllerHelpers
def login_patient
before :each do |example|
unless example.metadata[:skip_before]
@request.env["devise.mapping"] = Devise.mappings[:user]
@patient = FactoryGirl.create(:patient)
sign_in :user, @patient
end
end
end
end
答案 0 :(得分:1)
您在发送请求后创建记录,因此在请求完成时,您刚创建的记录不会包含在收藏夹列表中。将您的测试代码更改为以下
let!(:favorite) { FactoryGirl.create(:favorite) }
before { get :index }
it "assigns all favorites as @favorites" do
expect(assigns(:favorites)).to eq([favorite])
end
这可能仍会失败,因为assigns(:favorites)
是ActiveRecord::Relation
对象,因此您必须致电to_a
expect(assigns(:favorites).to_a).to eq([favorite])
更新:
由于患者正在过滤收藏,因此您必须确保测试中创建的收藏属于患者。您可以通过将收藏夹更改为
来实现let!(:favorite) { FactoryGirl.create(:favorite, patient: @patient)
答案 1 :(得分:0)
尝试在请求之前创建记录:
let!(:favorite) { FactoryGirl.create(:favorite) }
before(:each) { get :index }
it "assigns all favorites as @favorites" do
expect(assigns(:favorites).to_a).to eq([favorite])
end