【问题标题】:Rspec testing a before_create hookRspec 测试 before_create 钩子
【发布时间】:2016-02-04 18:02:42
【问题描述】:

我正在尝试从我的模型中测试下面看到的 set_random_token 方法

class Invitation < ActiveRecord::Base

      has_and_belongs_to_many :users

      validates :name, presence: true, uniqueness: true
      validates :number_of_uses, presence: true, numericality: true
      validates :token, presence: true, uniqueness: true, format: /\A[0-9A-F]+\z/i
      before_create :set_random_token

      private

      def set_random_token
        random_hex = SecureRandom.hex(8)
        self.token = random_hex
      end

    end

这是我的邀请规范中的部分

it 'verifies that the token is set' do
    @invitation = Invitation.new
    @invitation.save
    expect(@invitation.token).not_to be_empty
end

这是我遇到的错误

  2) Invitation verifies that the token is set
     Failure/Error: expect(@invitation.token).not_to be_empty
       expected  to respond to `empty?`
     # ./spec/models/invitation_spec.rb:37:in `block (2 levels) in <top (required)>'

我对 Rails 很陌生,所以如果答案非常明显,我深表歉意。

【问题讨论】:

  • 我怀疑您在保存之前遇到了验证错误。使用save! 而不是save 看看是不是这样。

标签: ruby-on-rails ruby rspec


【解决方案1】:

我曾经见过从记录的本地或实例变量检查属性/列的内容并没有产生相同的预期结果的时候。我过去使用的解决方法是使用.first 查询记录并检查其中的列。

为确保您确实获得了正确的记录,请在开头添加 expect(Table.count).to eq 0

试试这个

it 'verifies that the token is set' do
  expect(Invitation.count).to eq 0
  Invitation.new().save(validate: false)
  expect(Invitation.count).to eq 1
  expect(Invitation.first.token).not_to be_empty
end

【讨论】:

    【解决方案2】:

    来自Rails Documentation

    以下方法触发验证,仅当对象有效时才会将对象保存到数据库中:

    • 保存

    在您的测试中,您正在实例化一个空的 Invitation,但 Invitation 上有许多验证,这会使空的 Invitation 无效。

    试试这个:

    @invitation = Invitation.create({name: 'something unique', number_of_uses: 5})
    expect(@invitation.token).not_to be_empty
    @invitation.save
    

    【讨论】:

    • 你的建议是有道理的,但它似乎并没有奏效。它仍然给我同样的错误
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-27
    • 2021-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多