我有一个模型User
,该模型在创建后在回调中创建了选项
# User
has_one :user_options
after_create :create_options
private
def create_options
UserOptions.create(user: self)
end
我对此有一些简单的Rspec涵盖:
describe "new user" do
it "creates user_options after the user is created" do
user = create(:user)
user.user_options.should be_kind_of(UserOptions)
end
end
一切正常,直到我向用户模型添加了自定义验证。
validate :check_whatever, if: :blah_blah
现在规范失败了,唯一通过的方法是重新加载规范中的记录:
it "creates user_preferences for the user" do
user = create(:user)
user.reload
user.user_options.should be_kind_of(UserOptions)
end
这是什么原因呢?
首先,我建议阅读有关调试Rails应用程序的文章:http : //nofail.de/2013/10/debugging-rails-applications-in-development/
其次,我将对您的代码提出一些更改:
def create_options
UserOptions.create(user: self)
end
应该
def create_options
self.user_option.create
end
这样,您不必在保存后重新加载对象,因为该对象的关系中已经具有新的UserOptions实体。
从代码中假设create(:user)
您正在使用灯具。您在user.yml中使用的数据和编写的验证可能存在问题,但不幸的是没有在此处发布。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句