我是 Rails 新手,正在使用 Rails 进行实用敏捷 Web 开发中的 Depot 应用程序,但遇到了一个奇怪的问题。
在我的产品模型中,我创建了一个验证器,用于确认图像 url 字段中要求的图像确实作为资产存在。这是我的产品型号代码。
class Product < ActiveRecord::Base
attr_accessible :description, :image_url, :price, :title
validates :description, :price, :title, :presence => true
validate :image_url_exists, on: :create
def image_url_exists
if Rails.application.assets.find_asset(image_url) == nil
errors.add(:image_url, 'is not valid. The image does not exist.')
end
end
end
现在的问题是当我运行我的单元测试时。这是什么:
require 'test_helper'
class ProductTest < ActiveSupport::TestCase
test "the products attributes should not be empty" do
p = Product.new
assert p.invalid?
end
end
但是这样做会在我的代码中触发一堆错误。如果没有自定义验证器,一切似乎都可以正常工作。这是我目前遇到的错误。
test_the_products_attributes_should_not_be_empty(ProductTest):
TypeError: can't convert nil into String
/var/lib/gems/1.9.1/gems/sprockets-2.2.2/lib/sprockets/base.rb:156:in `initialize'
/var/lib/gems/1.9.1/gems/sprockets-2.2.2/lib/sprockets/base.rb:156:in `new'
/var/lib/gems/1.9.1/gems/sprockets-2.2.2/lib/sprockets/base.rb:156:in `find_asset'
/var/lib/gems/1.9.1/gems/sprockets-2.2.2/lib/sprockets/index.rb:60:in `find_asset'
/var/lib/gems/1.9.1/gems/sprockets-2.2.2/lib/sprockets/environment.rb:78:in `find_asset'
/home/saurabh/Desktop/SCRIPTS/Rails/depot/app/models/product.rb:6:in `image_url_exists'
/var/lib/gems/1.9.1/gems/activesupport-3.2.9/lib/active_support/callbacks.rb:418:in `_run__4343689776242734370__validate__107120755283260520__callbacks'
/var/lib/gems/1.9.1/gems/activesupport-3.2.9/lib/active_support/callbacks.rb:405:in `__run_callback'
/var/lib/gems/1.9.1/gems/activesupport-3.2.9/lib/active_support/callbacks.rb:385:in `_run_validate_callbacks'
/var/lib/gems/1.9.1/gems/activesupport-3.2.9/lib/active_support/callbacks.rb:81:in `run_callbacks'
/var/lib/gems/1.9.1/gems/activemodel-3.2.9/lib/active_model/validations.rb:228:in `run_validations!'
/var/lib/gems/1.9.1/gems/activemodel-3.2.9/lib/active_model/validations/callbacks.rb:53:in `block in run_validations!'
/var/lib/gems/1.9.1/gems/activesupport-3.2.9/lib/active_support/callbacks.rb:403:in `_run__4343689776242734370__validation__107120755283260520__callbacks'
/var/lib/gems/1.9.1/gems/activesupport-3.2.9/lib/active_support/callbacks.rb:405:in `__run_callback'
/var/lib/gems/1.9.1/gems/activesupport-3.2.9/lib/active_support/callbacks.rb:385:in `_run_validation_callbacks'
/var/lib/gems/1.9.1/gems/activesupport-3.2.9/lib/active_support/callbacks.rb:81:in `run_callbacks'
/var/lib/gems/1.9.1/gems/activemodel-3.2.9/lib/active_model/validations/callbacks.rb:53:in `run_validations!'
/var/lib/gems/1.9.1/gems/activemodel-3.2.9/lib/active_model/validations.rb:195:in `valid?'
/var/lib/gems/1.9.1/gems/activerecord-3.2.9/lib/active_record/validations.rb:69:in `valid?'
/var/lib/gems/1.9.1/gems/activemodel-3.2.9/lib/active_model/validations.rb:203:in `invalid?'