ruby 在Rails中运行测试时未定义方法

bogh5gae  于 12个月前  发布在  Ruby
关注(0)|答案(1)|浏览(124)

所以我想为我的程序编写测试,当我运行bin/rails test test/models/inventory_test.rb时,
我得到错误

# Running:

E

Error:
InventoryTest#test_quantity_should_not_be_negative:
NoMethodError: undefined method `variations' for #<#<Class:0x000000010862c9e8>:0x000000010864a290>
    test/fixtures/inventories.yml:2:in `get_binding'

现在我根据我的模型和库存创建了fixtures。yml看起来像这样:

one:
  variation_id: <%= variations(:one) %>
  warehouse_id: <%= warehouses(:one) %>
  quantity: 50
  updated_by_user_id: <%= users(:one) %>
  product_id: <%= products(:one) %>
  created_at: <%= fake_time %>
  updated_at: <%= fake_time %>

two:
  variation_id: <%= variations(:two) %>
  warehouse_id: <%= warehouses(:two) %>
  quantity: 100
  updated_by_user_id: <%= users(:two) %>
  product_id: <%= products(:two) %>
  created_at: <%= fake_time %>
  updated_at: <%= fake_time %>

现在我不知道为什么它试图得到变化的方法,我没有一个,我不知道如何调试这个。什么都试过了。
我的库存模型看起来像这样:

class Inventory < ApplicationRecord
  belongs_to :product
  belongs_to :warehouse
  belongs_to :variation
  belongs_to :updated_by, class_name: "User", foreign_key: "updated_by_user_id"

  has_many :inventory_transactions

  validates :quantity, presence: true, numericality: { only_integer: true, greater_than_or_equal_to: 0 }
  has_one :restock_alert, dependent: :destroy
  after_save :check_restock_alert

  def check_restock_alert
    if self.quantity <= self.restock_alert.threshold
      self.restock_alert.update(status: RestockAlert::TRIGGERED)
    elsif self.quantity > self.restock_alert.threshold
      self.restock_alert.update(status: RestockAlert::PENDING)
    end
  end
  
end

尝试在其他灯具中创建variation_id:一个等等,导致其他问题。这一个感觉像最接近我可以解决,但它检查的变化方法,我没有。

ipakzgxi

ipakzgxi1#

不知道为什么你在inventories.yml文件中使用.erb语法,因为它是不需要的。在fixture中,您可以创建通过关联相互引用的记录,而不必做那么多工作。所以,考虑到你的文件:

one:
  variation_id: <%= variations(:one) %>
  warehouse_id: <%= warehouses(:one) %>
  quantity: 50
  updated_by_user_id: <%= users(:one) %>
  product_id: <%= products(:one) %>
  created_at: <%= fake_time %>
  updated_at: <%= fake_time %>

如果你有一个这样的variations.yml:

one:
   foo: bar
   ...

您只需要在您的库存中执行此操作。yml

one:
  variation: one
  warehouse: one #assumes a warehouses.yml with a record with that name
  quantity: 50
  updated_by_user: one
  product: one
  created_at: <%= fake_time %>
  updated_at: <%= fake_time %>

相关问题