Topic: Unit testing - depot app of AGWDWR 4th ed

Having some issues with getting the unit tests to work. I started working on some of the bonus questions. For those that aren't familiar, the depot app is a simple store. It has products. Line items which belong to a cart and a product. A cart belongs to an order. As part of the bonus questions, I set up another model called PaymentType, which an order belongs to. My code on the site itself works just fine, it's the tests that are failing.

Here's my code:

class Order < ActiveRecord::Base
  has_many :line_items, :dependent => :destroy
  
  # PAYMENT_TYPES = ["Check", "Credit card", "Purchase order"]
  belongs_to :payment_type
  
  validates :name, :address, :email, :presence => true
  validates_inclusion_of :payment_type_id, :in => PaymentType.all.map { |type| type.id }, :message => "- Invalid payment type selected"
  
  
  def add_line_items_from_cart(cart)
    cart.line_items.each do |item|
      item.cart_id = nil
      line_items << item
    end
  end
end

order_test.rb

require 'test_helper'

class OrderTest < ActiveSupport::TestCase
  fixtures :orders
  fixtures :payment_types
  
  setup do
    @order = orders(:one)
  end
  
  test "order attributes must not be empty" do
    order = Order.new
    assert order.invalid?
    [:name, :address, :email, :payment_type].each do |sym|
      assert order.errors[sym].any?
    end
    
    # test fixture values
    assert @order.valid?
    assert_not_equal @order.payment_type.id, nil
    assert_not_equal @order.name, ''
    assert_not_equal @order.address, ''
    assert_not_equal @order.email, ''
  end
end

orders.yml (fixture) && payment_types.yml

one:
  name: Dave Thomas
  address: MyText
  email: dave@example.org
  payment_type: check 

two:
  name: MyString
  address: MyText
  email: MyString
  payment_type: check


check:
  name: Pay Check
# column: value
#
creditcard: 
  name: Credit Card

When i run rake test:units, i receive the following failure:

  1) Failure:
test_order_attributes_must_not_be_empty(OrderTest) [test/unit/order_test.rb:15]:
Failed assertion, no message given.

the line it refers to is: assert @order.valid?

Given the fixtures and test code. Do you have any ideas of what might be causing it to fail?

Re: Unit testing - depot app of AGWDWR 4th ed

Solved! big_smile

Found a solution online when i started looking into doing units tests with validates_inclusion_of. Since it's an association, the solution is to use:

validates_associated :payment_type

Makes sense really, as validates_inclusion_of is more for an array local to the model, not another model.