我最近开始在我的rspec输出中看到以下错误消息:
undefined method [] for nil:NilClass
注意这不会使测试失败,它只是将此错误消息放入缓冲区。我已经设法通过邮件追踪它正在发生的事情。但是,我似乎无法找到它可能产生的任何地方,或任何方式看到回溯。
请原谅大糊,但我想确保包含所有相关代码:
## app/models/invite.rb
class Invite < ActiveRecord::Base
include Token
belongs_to :account
after_create :send_email
def send_email
InviteMailer.invite(self).deliver
end
end
## app/mailers/invite_mailer.rb
class InviteMailer < ActionMailer::Base
def invite(invite)
@invite = invite
@account = invite.account
mail to: invite.email, subject: "You're invited to help manage #{@account.name}"
end
end
## spec/models/invite_spec.rb
require 'spec_helper'
describe Invite do
let(:account){create(:account)}
it 'mails the user' do
account.invites.create(email: 'my@email.com')
end
end
## config/environments/test.rb
config.action_mailer.default_url_options = { :host => 'localhost:3000' }
config.action_mailer.delivery_method = :test
## Test Results
› be rspec spec/models/invite_spec.rb
undefined method `[]' for nil:NilClass
undefined method `[]' for nil:NilClass
.
Finished in 0.79803 seconds
1 example, 0 failures
Randomized with seed 46468
感谢您的帮助,这个让我疯狂。
答案 0 :(得分:0)
建议更改let
invite_spec.rb
let!(:account){create(:account)}
让pang立刻创造它而不是懒惰。每当我得到nil:NillClass error
时,我都会检查一下。它容易被忽视。