【问题标题】:Representing has_many :though with Factory Bot代表 has_many :though with Factory Bot
【发布时间】:2018-07-09 18:51:20
【问题描述】:

鉴于模型设置如下:

class Course < ApplicationRecord
  belongs_to :faculty
  has_many :teachings
  has_many :faculty, through: :teachings

  validates :name, uniqueness: { scope: [:faculty_id, :period,
                                         :semester, :year] }
end

class Faculty < ApplicationRecord
  has_secure_password

  has_many :courses
  has_many :courses, :through => :teachings

  validates :email, { presence: true, uniqueness: true }
  validates :first_name, presence: true
  validates :last_name, presence: true
  validates :password, presence: true
end

我正在尝试像这样测试课程的创建:

RSpec.describe Course, :type => :model do

  it "is valid with when period and faculty are unique" do
    course = create(:course)
    expect(course).to be_invalid
  end
end

运行测试时出现以下错误:

1) 课程在期间和师资独特时有效 失败/错误: course = create(:course)

 ActiveRecord::RecordInvalid:
   Validation failed: Faculty must exist

我尝试过创建一个教师,并在创建课程时使用它,但仍然很幸运。

我已经查找了如何处理工厂机器人和关系并尝试了其中一些,但我对测试太无知,无法让它发挥作用。我希望能对我现在的情况有所了解。

【问题讨论】:

  • 我回答你的问题了吗?

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


【解决方案1】:

验证在保存时间运行,您想要做的是使用build

  it "is valid with when period and faculty are unique" do
    course = build(:course, faculty: create(:faculty))
    expect(course).to be_invalid
  end

这将在后台调用course.valid?,这是您要证明的。

【讨论】:

  • 感谢您的帮助,但现在我明白了。它似乎试图迭代单个对象? NoMethodError: undefined method each' for #<0x00007fc3f55908b0>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-19
  • 1970-01-01
  • 1970-01-01
  • 2019-10-29
相关资源
最近更新 更多