rspec-rails and factory girl block in <top (required)>': undefined method `build'
Asked Answered
I

1

6

I have a new Rails 4 project with FactoryGirl and rSpec. In my spec_helper.rb I have:

# lots of stuff
RSpec.configure do |config|
  # more stuff
  config.include FactoryGirl::Syntax::Methods
end

I also removed the rspec/autorun require in this file.

A simple spec:

require 'spec_helper'

describe User do
  build(:user)
end

with a simple factory:

FactoryGirl.define do
  factory :user do
    email     "[email protected]"
  end
end

Fails with the following message.

`block in <top (required)>': undefined method `build' for #<Class:0x007fd46d0e3848> (NoMethodError)

However, if I explicitly qualify build in the spec like this it passes:

require 'spec_helper'

describe User do
  FactoryGirl.build(:user)
end

What can I do so I don't have to add FactoryGirl every time?

Islean answered 30/1, 2014 at 23:53 Comment(0)
H
10

The methods passed to config.include are only included by RSpec within the it, let, before and after blocks, not at the top level of describe. Since that's where you generally need to put your setup and test logic, in practice it's not really an issue.

Haarlem answered 31/1, 2014 at 0:55 Comment(1)
<sheepish look> I was transitioning from Machinist to FactoryGirl and stuck what seemed like the simplest thing possible together so I could get a read on how this worked.Islean

© 2022 - 2024 — McMap. All rights reserved.