Szymon Borucki
Szymon Borucki

Reputation: 407

Factory_girl and RSpec: undefined method `new' for Test:Module

I generated the following scaffold (using Ruby 2.2.0, rails 4.1.8, postgres):

 rails g scaffold Test user:references text:references data:hstore

In my test_spec.rb:

require 'rails_helper'

RSpec.describe Test, :type => :model do
  describe 'User generates a test' do
    before do
      @text = create(:text, content: "Cats eat mice")
      @user = create(:user)
      @test = create(:test)
    end
...

When I run rspec the test fails with the following message:

Failure/Error: @test = create(:test)
 NoMethodError:
   undefined method `new' for Test:Module
 # ./spec/models/test_spec.rb:8:in `block (3 levels) in <top (required)>'

When I test other models (user, text) everything works well, only the Test model fails. Calling Test.create(...) in rspec file also fails. Creating new test in rails console works. Any ideas how to fix this?

Upvotes: 0

Views: 1518

Answers (1)

Peter Alfvin
Peter Alfvin

Reputation: 29379

With the default configuration, Rails defines the module constant Test, so Ruby doesn't autoload your test.rb file when FactoryGirl does a Test.new as part of your :test factory.

You can install Rails without the Test infrastructure by using the -T switch, in which case it won't define the Test module and you should be fine.

If Rails is already configured, you can put the following in your rails_helper.rb file to remove the Test constant and you should be ok as well:

Object.send(:remove_const, :Test)

Upvotes: 1

Related Questions