【问题标题】:How to create factories with attr_accessible?如何使用 attr_accessible 创建工厂?
【发布时间】:2012-06-25 09:12:57
【问题描述】:

如何与工厂和attr_accessible打交道?

我的例子:

# model
class SomeModel

  attr_accessible :name, full_name, other_name

end

#spec
require 'spec_helper'

describe "test" do
  it do
    create(:some_model, name: "test name", user: User.first) #factory
  end

end

#error
ruby(17122,0x12a055000) malloc: *** error for object 0x8: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug

我认为错误是因为user_id 不在attr_accessible 属性中。

【问题讨论】:

  • 如果这是问题,活动记录会引发异常 - 您不会遇到 C 级崩溃。根据定义,这些几乎都是 ruby​​ 中的错误(或 ruby​​ 扩展)或 ruby​​ 在您的机器上构建的问题
  • 有没有机会调试一下出了什么问题?
  • 为什么不能在模型中的 attr_accessible 中添加一个:user_id?您不会在代码中使用 user_id 创建 SomeModel 实例吗?
  • @alony:因为随意给attr_accessible添加属性违背了它的目的。如果添加了user_id(注意:您实际上必须为他的代码添加user),那么用户可以在他们的哈希中添加一个user_id 参数并将关联设置为他们想要的任何用户。当然,您可以通过这样的关联范围来防止这种情况发生:@user.some_models.create FactoryGirl.attributes_for(:some_model, name: "test name")

标签: ruby-on-rails ruby ruby-on-rails-3 rspec factory-bot


【解决方案1】:

好的,但无论如何,如果您使用关联定义您的工厂,即使使用attr_protected,它也应该分配记录

factory :some_model do |sm|

  sm.name "John"
  sm.full_name "John Smith"
  sm.other_name  "some other"

  sm.association :user, :factory => :user
end

describe "test" do
  it "should create models with associations" do
    Factory(:some_model, name: "test name", user: User.first) #factory
  end
end

【讨论】:

    【解决方案2】:

    这似乎与我因 attr_accessible 而得到的不同。 但是,您可以简单地将 :user 添加到 attr_accessible

    【讨论】:

      【解决方案3】:

      您不只需要 SomeModel 中的那个吗?

      belongs_to :user
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-02-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-10
        • 1970-01-01
        • 1970-01-01
        • 2022-06-11
        相关资源
        最近更新 更多