【问题标题】:Rails error ActiveRecord::AssociationTypeMismatch: User(#65709220) expected, got String(#19934580)Rails 错误 ActiveRecord::AssociationTypeMismatch: 预期用户(#65709220),得到字符串(#19934580)
【发布时间】:2013-09-06 05:00:29
【问题描述】:

你好,在 rails 中使用 rspec 并创建一个有效用户,如下所示

it "should create a valid user" do
    @user = User.find_or_create_machine_user("test@dllo.no","test_first",     "test_last").should be_an_instance_of User
  end

这个测试通过并且工作正常,但是当我包含这个部分时,我得到一个错误

 @batch = FactoryGirl.create(:batch, :file_name => "test_file",
                                  :created_by=> @user)

然后说ActiveRecord::AssociationTypeMismatch: User(#65709220) expected, got String(#19934580)。我尝试使用 created_by_id = @user.id.to_int 这也失败了。

架构

class Batch < ActiveRecord::Base
  belongs_to :created_by, :class_name => "User", :foreign_key => :created_by
  attr_accessible :created_by, :file_name

谁能告诉我如何克服这个问题? created_by 接受用户

【问题讨论】:

  • 如果您可以分享您的整个规范以及您在使用 @user.id.to_int 时遇到的具体错误,将会有所帮助。
  • 和您的相关模型/模式,以便我们可以看到您正在使用什么。
  • User.find_or_create_machine_user的定义是什么?
  • 它将创建一个有效的用户 :) 该函数工作正常并返回一个用户对象

标签: ruby-on-rails rspec rspec2


【解决方案1】:

您的规范正在将断言的值分配给@user。 @user 因此不是用户。另外,find_or_create_machine_user 看起来很奇怪。您应该使用find_or_create_by 的变体,或者更好地为用户编写一个工厂。传递 User 类的这个实际实例应该可以解决问题。

it "should create a valid user" do
  @user = User.find_or_create_machine_user("test@dllo.no","test_first","test_last")
  @user.should be_an_instance_of User
end

【讨论】:

  • 我通过了一个实际的用户类,它说用户需要一个字符串
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-01
  • 1970-01-01
相关资源
最近更新 更多