Rspec测试before_create钩子

时间:2016-02-04 18:02:42

标签: ruby-on-rails ruby rspec

我试图从我的模型中测试下面看到的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

以下是我的invitation_spec

中的内容
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很陌生,所以如果答案非常明显,我会道歉。

2 个答案:

答案 0 :(得分:2)

我已经看到从记录的本地或实例变量检查属性/列的内容并没有产生相同的预期结果的时间。我过去使用的解决方法是使用<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" indent="yes"/> <xsl:template match="ansokan"> <begaranominkomstuppgift> <xsl:for-each select="vardnadshavare"> <person> <xsl:attribute name="personnummer"> <xsl:value-of select="@personnummer"/> </xsl:attribute> <fornamn> <xsl:value-of select="fornamn"/> </fornamn> <efternamn> <xsl:value-of select="efternamn"/> </efternamn> </person> </xsl:for-each> </begaranominkomstuppgift> </xsl:template> </xsl:stylesheet> 查询记录并检查该列。

为确保您实际获得正确的记录,请在开头添加.first

试一试

expect(Table.count).to eq 0

答案 1 :(得分:0)

来自Rails Documentation

  

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

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

请改为尝试:

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