0

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.

Simone Carletti
  • 173,507
  • 49
  • 363
  • 364
tomekfranek
  • 6,852
  • 8
  • 45
  • 80
  • 1
    If that was the problem active record would raise an exception - you wouldn't get a C level crash. Those are pretty much by definition either a bug in ruby (or an ruby extension) or a problem with how ruby was built on your machine – Frederick Cheung Jun 25 '12 at 09:27
  • Is there a chance to debug what`s going wrong? – tomekfranek Jun 25 '12 at 09:37
  • why can't you just add a `:user_id` to attr_accessible in the model? Won't you be creating SomeModel instances with user_id in the code? – alony Jun 25 '12 at 10:16
  • @alony: Because arbitrarily adding attributes to `attr_accessible` defeats the purpose of it. If `user_id` is added (note: you'd actually have to add `user` for his code), then users could add a `user_id` param in their hash and set the association to any user they wanted. Of course, you could prevent that by scoping associations like this: `@user.some_models.create FactoryGirl.attributes_for(:some_model, name: "test name")` – danneu Jun 25 '12 at 16:17

3 Answers3

2

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
alony
  • 10,725
  • 3
  • 39
  • 46
0

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

davidrac
  • 10,723
  • 3
  • 39
  • 71
0

Don't you just need that in SomeModel?

belongs_to :user
Wawa Loo
  • 2,266
  • 18
  • 15