我正在尝试测试以下控制器操作(使用Ruby on Rails,RSPEC和FactoryGirl):
class ContactsController < ApplicationController
before_action :authenticate_user!
def index
@contacts = current_user.contacts
# @contacts = Contact.all
end
这是我的contacts_controller_spec.rb文件:
require 'rails_helper'
describe ContactsController do
before do
@user = FactoryGirl.create(:user_with_contacts)
sign_in @user
end
describe "GET INDEX" do
it "assigns @contacts" do
expect(assigns(:contacts)).to eq(@user.contacts)
end
end
Failure/Error: expect(assigns(:contact)).to eq([contact])
expected: [#<Contact id: 295, first_name: "Loy", email: "leon@hegmannhintz.net", phone_number: "6044339393", created_at: "2015-09-12 19:13:42", updated_at: "2015-09-12 19:13:42", last_name: "Wyman", user_id: 343>]
got: #<Contact id: nil, first_name: nil, email: nil, phone_number: nil, created_at: nil, updated_at: nil, last_name: nil, user_id: nil>
这是我的users_spec.rb文件:
FactoryGirl.define do
factory :user do
email { Faker::Internet.email }
password { "32423fdsfasf42" }
factory :user_with_contacts do
transient do
contacts_count 2
end
after(:create) do |user, evaluator|
create_list(:contact, evaluator.contacts_count, user: user)
end
end
end
end
请帮忙吗?我已经坚持了很长时间。
如果我打电话
puts @user.inspect
我得到了
#<User id: 340, email: "johnson_kaulke@brekke.com", encrypted_password: "$2a$04$Si5k6Q1eYERvhQITXKBoIOGEzPyK50E3IQ.yjRcqmDj...", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 0, current_sign_in_at: nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: nil, created_at: "2015-09-12 19:13:42", updated_at: "2015-09-12 19:13:42">
和
致电
puts @user.contacts.inspect
我得到了
#<ActiveRecord::Associations::CollectionProxy [#<Contact id: 289, first_name: "Fae", email: "ariane@johnston.net", phone_number: "6044339393", created_at: "2015-09-12 19:13:42", updated_at: "2015-09-12 19:13:42", last_name: "Spinka", user_id: 340>, #<Contact id: 290, first_name: "Marcellus", email: "chloe_deckow@buckridge.net", phone_number: "6044339393", created_at: "2015-09-12 19:13:42", updated_at: "2015-09-12 19:13:42", last_name: "Bashirian", user_id: 340>]>
当我打电话给分配(:联系人)时,问题就发生了!
答案 0 :(得分:0)
我想你忘了调用控制器动作了。 :)
尝试添加get :index
it "assigns @contacts" do
get :index
expect(assigns(:contacts)).to eq(@user.contacts)
end