Home > OS >  Undefined method while checking attribute value with Rspec in Rails
Undefined method while checking attribute value with Rspec in Rails

Time:09-24

I am new to ruby, rails and rspec. I want to verify that card numbers have been truncated after they have been saved.

Here is my test code:

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 => "[email protected]",
        :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

Which gives me the error:

undefined method `card_number' for true:TrueClass

Any idea what I'm doing wrong here?

CodePudding user response:

You're assigning the result of #save to @payment:

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

So do it in two steps:

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