RSpec测试因NoMethodError而失败

时间:2017-02-17 09:28:28

标签: ruby-on-rails ruby rspec

我有一个模型domain.rb

class Domain < ActiveRecord::Base
  belongs_to :user
  has_many :ranks, dependent: :destroy

  validates_uniqueness_of :name, scope: :user_id, message: "You alredy entered that domain"
  validates_presence_of :name
  validate :user_quota, on: :create

  def user_quota
    errors.add(:base, 'OOps!!! You have Exceeded maximum domain limit/user (3)')  if self.user.domains(:reload).count >= 3
  end
end

在我的domain_spec.rb我正在尝试测试自定义验证 - 唯一用户只能有3个域

require 'rails_helper'

RSpec.describe Domain, type: :model do
  it " - cannot create a new domain if user already have 3 domains" do

    user = User.create(name: "John Doe", email: 'jane@doe.com', password: 'pw1234',
    password_confirmation: 'pw1234')

    user_domain1 = Domain.create(name: 'http://example1.com', user_id: user.id,
               created_at: DateTime.now, updated_at: DateTime.now)
    expect(user_domain1.errors).to be_empty

    user_domain2 = Domain.create(name: 'http://example2.com', user_id: user.id,
               created_at: DateTime.now, updated_at: DateTime.now)
    expect(user_domain2.errors).to be_empty

    user_domain3 = Domain.create(name: 'http://example3.com', user_id: user.id,
               created_at: DateTime.now, updated_at: DateTime.now)
    expect(user_domain3.errors).to be_empty

    user_domain4 = Domain.create(name: 'http://example4.com', user_id: user.id,
               created_at: DateTime.now, updated_at: DateTime.now)
    expect(user_domain4.errors).to_not be_empty

  end
end

运行我的测试时rspec spec/models/domain_spec.rb我收到错误:

  

域 - 如果用户已有3个域

,则无法创建新域
 Failure/Error: errors.add(:base, 'OOps!!! You have Exceeded maximum
 domain limit/user (3)')  if self.user.domains(:reload).count >= 3
 NoMethodError: undefined method `domains' for nil:NilClass

我的user.rb

class User < ActiveRecord::Base
  has_many :domains
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
       :recoverable, :rememberable, :trackable, :validatable, :confirmable, :lockable, :zxcvbnable

  # Override Devise method to send mails in background
  def send_devise_notification(notification, *args)
    devise_mailer.send(notification, self, *args).deliver_later
  end
end

我做错了什么?我是RSpec的新手,请帮我解决这个问题。提前谢谢

1 个答案:

答案 0 :(得分:1)

查看错误消息:

[...] self.user.domains(:reload).count >= 3
  NoMethodError: undefined method `domains' for nil:NilClass

这表示user未保存,可能是因为某些验证错误。现在的挑战是找出为什么验证失败,以便您可以修复它。

在测试代码中,您将按如下方式创建这些数据库条目:

user = User.create(name: "John Doe", ...)
user_domain1 = Domain.create(name: 'http://example1.com', user_id: user.id, ...)

使用create! instead of create

的一种简单方法来了解正在发生的错误,以便您的测试失败并提供更有帮助的消息
user = User.create!(name: "John Doe", ...)
user_domain1 = Domain.create!(name: 'http://example1.com', user_id: user.id, ...)

通过这样做,将引发RecordInvalid异常,说明无法保存记录的原因。