我有一个属于课程,教师和学期的模型部分。
我的Factory Girl定义如下:
factory :section do
course
teacher
semester
sequence(:section_number) {|n| "n"}
days_of_week ["M", "W", "F", ""]
time_block "7:45-9:15"
end
我没有任何相关模型或部分的唯一性验证。
我有2个rspec文件,我需要创建一个部分。如果我单独在每个文件上运行rspec,它们都会通过,但如果我在整个目录上运行rspec,则每次都会失败,因为section是nil。它也不是每次都失败的同一个文件......
Failure/Error: section = FactoryGirl.create(:section)
NoMethodError:
undefined method `join' for nil:NilClass
即使我在rails控制台中调用Factory Girl,它也会正确创建第一部分,任何后续调用都会产生零部分。
我不知道为什么会发生这种情况......我有很多其他工厂正常工作。
答案 0 :(得分:0)
您的后续selection
工厂永远不会是唯一的。您对sequence
使用section_number
,但最终使用String
" n"。
尝试替换
sequence(:section_number) {|n| "n"}
与
sequence(:section_number) {|n| n}
而是看看它是否适合你。
答案 1 :(得分:0)
问题不在我的工厂,正如我原先怀疑的那样。
我在section.rb上有一个before_create方法,它将数组转换为字符串。我改变了工作方式,解决了问题。
之前:
class Section < ActiveRecord::Base
serialize :days_of_week
before_create :array_to_s
belongs_to :course
belongs_to :teacher
belongs_to :semester
has_many :student_section_enrollments
has_many :students, :through => :student_section_enrollments
WEEKDAYS = ["M", "TU", "W", "TH", "F"]
TIME_BLOCKS = ["7:45-9:15", "9:30-11:00"]
def set_next_section_number(semester)
self.section_number = semester.sections.count + 1
end
def current_semester_sections
@current_sections = Section.where("description LIKE ?", current_semester)
end
private
def array_to_s
self.days_of_week = self.days_of_week.reject!(&:empty?)
self.days_of_week = self.days_of_week.join(', ')
end
端
之后:
class Section < ActiveRecord::Base
serialize :days_of_week, Array
before_save :remove_empty_days_of_week
belongs_to :course
belongs_to :teacher
belongs_to :semester
has_many :student_section_enrollments
has_many :students, :through => :student_section_enrollments
WEEKDAYS = ["M", "TU", "W", "TH", "F"]
TIME_BLOCKS = ["7:45-9:15", "9:30-11:00"]
def set_next_section_number(semester)
self.section_number = semester.sections.count + 1
end
def current_semester_sections
@current_sections = Section.where("description LIKE ?", current_semester)
end
def days_of_week_string
days_of_week.join(', ')
end
private
def remove_empty_days_of_week
if self.days_of_week.present?
self.days_of_week.reject!(&:empty?)
end
end
end