How to create factories with attr_accessible?

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-25 06:58:29

问题


How to deal with factories and attr_accessible?

My example:

# 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

I think the error is because user_id is not in attr_accessible attributes.


回答1:


ok, but anyway if you define your factory with the association, it should assign the record even with 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

and than

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



回答2:


This seems different from what I got due to attr_accessible. However, you can simply add :user to attr_accessible




回答3:


Don't you just need that in SomeModel?

belongs_to :user


来源:https://stackoverflow.com/questions/11186425/how-to-create-factories-with-attr-accessible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!