我正在编写一个控制器规范,我首先创建一个3 @users
的数组。看起来像这样:
describe 'POST #create' do
context 'when invited user IS an existing user' do
before :each do
@users = [
attributes_for(:user),
attributes_for(:user),
attributes_for(:user)
]
end
it 'correctly finds User record of invited user' do
login_user
post :create, { email: @users.first[:email] }
invited_user = User.find_by(email: controller.params[:email])
expect(invited_user).to be_a(User)
end
end
end
当我使用此测试运行rspec
时,它会失败并给我这个错误:
1) Users::InvitationsController POST #create when invited user IS an existing user correctly finds User record of invited user
Failure/Error: expect(invited_user).to be_a(User)
expected nil to be a kind of User(id: integer, email: string, encrypted_password: string, reset_password_token: string, reset_password_sent_at: datetime, remember_created_at: datetime, sign_in_count: integer, current_sign_in_at: datetime, last_sign_in_at: datetime, current_sign_in_ip: string, last_sign_in_ip: string, created_at: datetime, updated_at: datetime, first_name: string, confirmation_token: string, confirmed_at: datetime, confirmation_sent_at: datetime, unconfirmed_email: string, invitation_relation: string, avatar: string, invitation_token: string, invitation_created_at: datetime, invitation_sent_at: datetime, invitation_accepted_at: datetime, invitation_limit: integer, invited_by_id: integer, invited_by_type: string, invitations_count: integer, bio: text, last_name: string, gender: integer)
以下是:user
的工厂:
factory :user do
association :family_tree
first_name { Faker::Name.first_name }
last_name { Faker::Name.last_name }
email { Faker::Internet.email }
password "password123"
password_confirmation "password123"
bio { Faker::Lorem.paragraph }
invitation_relation { Faker::Lorem.word }
# required if the Devise Confirmable module is used
confirmed_at Time.now
gender 1
end
我相信,正在发生的事情是User.find_by
ActiveRecord查找返回nil。
但如果我在上面创建了这3个用户记录,为什么会返回nil?