我有一个模型 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 中使用的数据和您编写的验证可能存在问题,但不幸的是没有在此处发布。
关于ruby-on-rails - 为什么我必须在使用客户验证器后重新加载 rspec 中的记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20032049/