Ruby on rails 为什么在使用客户验证器后必须在rspec中重新加载记录?

Ruby on rails 为什么在使用客户验证器后必须在rspec中重新加载记录?,ruby-on-rails,ruby,rspec,Ruby On Rails,Ruby,Rspec,我有一个模型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" d

我有一个模型
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应用程序的文章:

其次,我建议对您的代码进行一些更改:

def create_options
  UserOptions.create(user: self)
end
应该是

def create_options
  self.user_option.create
end
这样,您就不必在保存后重新加载对象,因为对象的关系中已经有了新的UserOptions实体


从代码
create(:user)
假设您正在使用装置。您在user.yml中使用的数据和您编写的验证可能有问题,但遗憾的是没有在此处发布。

发布rspec输出并显示失败消息。