【问题标题】:Inclusion in validation and Rspec using FactoryGirl使用 FactoryGirl 包含在验证和 Rspec 中
【发布时间】:2014-07-19 19:32:48
【问题描述】:

我在使用 Factory Girl 和 Rspec 在 Rails 中测试 ActiveRecord 包含验证时遇到问题。包含验证总是失败。这是我的代码:

class FruitType
  has_many :fruits
end

class Fruit
  belongs_to :fruit_type
  validates :fruit_type_id, numericality: { only_integer: true }
  validates :fruit_type_id, inclusion: { in: FruitType.pluck(:id), message: "is invalid" }
end

FactoryGirl.define do
  factory :fruit_type_apple, class: FruitType do
     name "Apple"
  end
end

FactoryGirl.define do 
  factory :valid_fruit, class: Fruit do
    name "Red Apple"
    association :fruit_type, factory: :fruit_type_apple
  end
end

Rspec 测试是:

it "should have valid factory" do
  f = FactoryGirl.build( :valid_fruit )
  puts f.fruit_type_id
  puts "\n#{FruitType.all.pluck(:id)}"
  expect(f).to be_valid
end

结果是:

1

[1] 楼…………

失败:

1) 验证后的水果应具有有效的工厂 失败/错误:expect(f).to be_valid 预期 # 有效,但出现错误:水果类型无效

如您所见,我在测试中打印出 Fruit Type id 列表,其中仅包含 1。我打印出水果的 fruit_type_id 值,即 1。然而,包含验证仍然失败。

如果我只是通过手动创建水果和类型在 Rails 控制台中做同样的事情,验证工作正常,只是在我运行测试时我看到了这种行为。有任何想法吗?我一定错过了关于工厂女孩的一些东西。

【问题讨论】:

    标签: ruby-on-rails rspec factory-bot


    【解决方案1】:

    您不应验证 fruit_type_id 属性,而应使用存在验证

    validates :fruit_type, presence: true
    

    【讨论】:

    • 您是说要删除验证中的数字性和包含性,并用简单的存在代替吗?这是否会验证这两种情况(用户输入了“A”作为fruit_type_id,或者他们输入了9999 作为fruit_type_id,而我没有那种类型的水果)?
    • 是的,两者都删除。尝试使用错误的值,然后自己看看。
    • 天哪。我可以给你小费吗?你的建议奏效了。出现了一个简单的 Google 搜索(关于验证存在):“验证指定的属性不是空白的(由 Object#blank 定义?),并且,如果属性是关联,则关联的对象未标记为销毁” apidock.com/rails/ActiveRecord/Validations/ClassMethods/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-13
    相关资源
    最近更新 更多