0

I have a Model that looks like this

class Course < ActiveRecord::Base
  attr_accessible :name
end

And my factories.rb looks like this

FactoryGirl.define do
  factory :course do
    name "testname"
  end
end

Then when I call FactoryGirl.create(:course) in Cucumber like so:

Given /^there are courses in the database$/ do
    FactoryGirl.create(:course)
end

I receive an undefined method error:

undefined method `name=' for #<Course id: nil, created_at: nil, updated_at: nil> (NoMethodError)

It all works fine when I use attr_accessor instead of attr_accessible in the Model, but according to other examples I've found it should work with both. Is this a bug or am I doing something wrong?

Links to examples where they say it should work:

How to create factories with attr_accessible?

https://groups.google.com/forum/#!topic/factory_girl/gjLXp96Acyg

https://gist.github.com/334413/2a0f60a9afbff321d3e96727ec17bab53c484128

Community
  • 1
  • 1
Niwsters
  • 3
  • 2

1 Answers1

1

Either should work provided that the fields in question exist in your database. ActiveRecord generates accessors (which FactoryGirl depends on) for attributes specified in attr_accessible but only if they are defined in the associated database table.

Peter Alfvin
  • 28,599
  • 8
  • 68
  • 106
  • Added links to some examples now. – Niwsters Jun 22 '13 at 18:13
  • Ok, this is indeed a little confusing and I'm not sure I have it right. In addition to the references you provided, see http://stackoverflow.com/questions/4700785/using-attr-accessor-and-attr-accessible-on-the-same-field. In short, I believe either should indeed work, provided that there are columns in the associated database table. That is, I believe ActiveRecord will provide the accessors for any database fields that are `attr_accessible`. I'll update my answer, but can you check to see if you've got the database set up properly (e.g. have migrated `name`). – Peter Alfvin Jun 22 '13 at 19:35
  • Ah yes, it seems the database wasn't migrated properly. The `schema.rb` file was lacking the name column, and re-migrating with `rake db:rollback` and `rake db:migrate` fixed it. Thanks a bunch! – Niwsters Jun 22 '13 at 21:26