Using factory_girl_rails with Rspec on namespaced models

橙三吉。 提交于 2019-12-03 22:04:20

I have a minimal working example here, maybe you could use it to pinpoint where your problem is. The comment you left on dmarkow's answer suggests to me that you have an error someplace else.

app/models/bar/foo.rb

class Bar::Foo < ActiveRecord::Base
end

*db/migrate/20110614204536_foo.rb*

class Foo < ActiveRecord::Migration
  def self.up
    create_table :foos do |t|
      t.string :name
    end
  end

  def self.down
    drop_table :foos
  end
end

spec/factories.rb

Factory.define :foo, :class => Bar::Foo do |f|
  f.name 'Foooo'
end

*spec/models/foo_spec.rb*

require 'spec_helper'

describe Bar::Foo do

  it 'does foo' do
    foo = Factory(:foo)
    foo.name.should == 'Foooo'
  end
end

Running the test:

$ rake db:migrate
$ rake db:test:prepare
$ rspec  spec/models/foo_spec.rb 
.

Finished in 0.00977 seconds
1 example, 0 failures

Hope it helps.

I think maybe FactoryGirl changes since this answer was posted. I did to make it work

Factory.define do
  factory :foo, :class => Bar::Foo do |f|
    f.name 'Foooo'
  end
end

With the current latest version of FactoryGirl (4.5.0), this is the syntax:

FactoryGirl.define do
  factory :client1_ad, class: Client1::Ad do |f|
    f.title       "software tester"
    f.description "Immediate opening"
  end
end

Notice that client1_ad can be whatever name you want coz we already force identifying its class name.

I found this question looking into a related issue with FactoryGirl and after a little reading of the source I figured out I could solve my problem by renaming my factories.

When I had model classes that were namespaced inside modules, eg: Admin::User I should have been defining my factories like this:

factory :'admin/user', class: Admin::User do
  #...
end

Rather than:

factory :admin_user, class: Admin::User do
  #...
end

Maybe this little tidbit of info might help someone someday. The specifics of my issue was that I was trying to use build(described_class) to build instances from factories in my RSpec specs and this works just fine with un-namespaced classes but not with classes inside modules. The reason is that internally when looking up factories FactoryGirl will use ActiveSupport's underscore helper to normalise the factory name.

Have you tried passing the actual class, rather than a string with the class name:

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