使用 Rails 中的 Rspec 检查属性值时未定义的方法

Undefined method while checking attribute value with Rspec in Rails

我是 ruby、rails 和 rspec 的新手。我想验证卡号保存后是否被截断

这是我的测试代码:

RSpec.describe Payment, type: :model do
  context 'after saving' do  # (almost) plain English
    it 'card number is truncated' do   #
      @payment = Payment.new(
        :card_number => "5520000000000000",
        :card_name => "Tom Jones",
        :card_security_code => "123",
        :card_expiry => "10/30",
        :email => "test@mail.com",
        :address_line1 => "400 Test Lane",
        :state => "WA",
        :postcode => "6000",
        :country => "Australia",
        :status => "processing"
      ).save(validate: false)
      expect(@payment.card_number).to eq('0000')
    end
  end
end

这给了我错误:

undefined method `card_number' for true:TrueClass

知道我做错了什么吗?

您正在将 #save 的结果分配给 @payment:

@payment = Payment.new(...).save(validate: false)

所以分两步进行:

@payment = Payment.new(
  :card_number => "5520000000000000",
  :card_name => "Tom Jones",
  :card_security_code => "123",
  :card_expiry => "10/30",
  :email => "test@mail.com",
  :address_line1 => "400 Test Lane",
  :state => "WA",
  :postcode => "6000",
  :country => "Australia",
  :status => "processing"
)
@payment.save(validate: false)