【发布时间】:2016-04-11 12:59:11
【问题描述】:
我正在使用 gem Frozen Record 来在我的 Rails 应用程序中设置一系列不变的问题,这些问题将被其他模型访问和使用。鉴于我习惯于测试驱动开发,在添加 Frozen Record gem 之前,我已经设置了一系列测试和验证:
class Question < FrozenRecord::Base
validates :next_question_id_yes, :question_text, :answer_type, presence: true
end
还有测试:
require 'rails_helper'
RSpec.describe Question, :type => :model do
let(:question) {Question.new(id: "1", question_text: "who's the daddy?", answer_type: 'Boolean', next_question_id_yes: '7', next_question_id_no: "9")}
it 'is valid' do
expect(question).to be_valid
end
#questions can be valid without a next_question_id_no, because some questions just capture info
#questions must have a next_question_id_yes as that will route them to the subsequent question
#if it's the last question in a block, we will use the next number up to signify the questions are complete
it 'is invalid without a next_question_id_yes' do
question.next_question_id_yes = nil
expect(question).to_not be_valid
end
it 'is invalid without a question_text' do
question.question_text = nil
expect(question).to_not be_valid
end
it 'is invalid without an answer_type' do
question.answer_type = nil
expect(question).to_not be_valid
end
end
当我拥有class Question < ActiveRecord::Base 时,所有这些都通过了,但自从成为 FrozenRecord 我得到:
rbenv/versions/2.1.2/lib/ruby/gems/2.1.0/gems/frozen_record-0.4.0/lib/frozen_record/base.rb:78:in `method_missing': undefined method `validates' for Question:Class (NoMethodError)
我认为 Frozen Record 中没有任何方法可以验证这些列的存在。我不太确定的是:
- 我是否需要对通过 YAML 加载的静态数据执行验证?我的第一感觉是,这将是对我的 YAML 代码的额外检查。
- 如果可以,我可以编写自定义验证来检查这些数据吗?
- 有没有其他人使用过这个 gem 并使用 Rspec 解决了这个问题? (根据 RubyGems,它已被下载数千次)
任何帮助将不胜感激。
【问题讨论】:
标签: ruby-on-rails validation rspec yaml