ruby-on-rails - 为什么我必须在使用客户验证器后重新加载 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" 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/

相关文章:

ruby-on-rails - 如何在 rspec 测试中输出变量?

ruby-on-rails - Rails 3 Autotest 说 "command not found",有什么想法吗?

javascript - 如何在 rails 中降级到较低版本的 jquery?

ruby - respond_to 和 respond_to_missing 有何不同?

rspec - Rspec 中的命令式和声明式步骤

ruby-on-rails - 如何扩展 Rails 应用程序

javascript - 从本地主机上的 Rails Controller 执行时,PhantomJS 脚本挂起

ruby-on-rails - rails : Auto-login already signed up user (Facebook/linkedin omniauth)

ruby-on-rails - 如何在 haml 中转义注释?

ruby-on-rails - <% %>(不等于)在 ruby​​ erb 中意味着什么?