gpt4 book ai didi

ruby-on-rails - RSpec with Factory_girl - 销毁对象

转载 作者:行者123 更新时间:2023-12-04 06:05:48 26 4
gpt4 key购买 nike

我不想测试两个模型之间的关系。A course has many enrollments, an enrollment has one course.
当类(class)被销毁时,与其相关的所有注册都将设置为 active = false .这适用于真实物体,我只是无法让测试工作,因为无论我做什么,类(class)都不会被破坏。

describe Enrollment do
it "deactivates enrollment" do
course = create(:a_course)
user = create_user
enrollment = build(:enrollment)
enrollment.course = course
enrollment.user = user
enrollment.save

# until now everything works as expected

expect { course.destroy }.to change { enrollment.active }.to be_false

# the course isn't being destroyed when calling course.destroy

end
end

我在 factory_girl 文档中找不到任何关于销毁 factory_girl 对象的信息,也许我做错了,我应该使用“真实”对象?谢谢!

更新
这是发生变化的模型
class Course < ActiveRecord::Base
attr_accessible ...

has_many :users, through: :enrollments
has_many :enrollments

before_destroy :deactivate_enrollments

protected

def deactivate_enrollments
enrollments = self.enrollments

enrollments.each do |e|
e.active = false
e.save
end
end
end

由于我对此不太确定,因此我用来测试的类(class)是 factory_girl 对象。它不是这样创建的: Course.create... . factory_girl 对象是否与 ActiveRecord 对象具有相同的方法?

这是 factory_girl代码:
FactoryGirl.define do
factory :course, class: Course do
titel "Course title"
end
end

更新 2
这是 failure message
Enrollment
deactivates enrolment (FAILED - 1)

Failures:

1) Enrollment deactivates enrollment
Failure/Error: expect { course.destroy }.to change(enrollment, :active).from(true).to(false)
active should have been changed to false, but is now true
# ./spec/models/enrollment_spec.rb:18:in `block (2 levels) in <top (required)>'

更新 3

事实证明,类(class)并没有被破坏。都没有 Course.destroy_allcourse.destroy作品。无论我是否创建类(class)并注册 factory_girl。怎么会这样?

最佳答案

更新

我注意到您通过重新加载注册回答了您自己的问题,但即便如此,我认为您应该更改 rspec 语法以使其更具可读性和表现力。最终结果可能是:

expect { 
course.destroy
enrollment.reload
}.to change(enrollment, :active).from(true).to(false)

我认为这将是记录代码行为的更好方法,因为它读起来几乎像流利的英语;)

关于ruby-on-rails - RSpec with Factory_girl - 销毁对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21785507/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com