railstutorial.org - undefined method `Factory'

会有一股神秘感。 提交于 2019-12-03 12:41:47
BvuRVKyUVlViVIc7

Maybe you should try the new syntax (see github readme of factory girl)

FactoryGirl.define :user do |user|
  user.name                  "Michael Hartl"
  user.email                 "mhartl@example.com"
  user.password              "foobar"
  user.password_confirmation "foobar"
end

As per the latest version of Factory Girl (currently v4.0.0) rewrite factories.rb

FactoryGirl.define do 
  factory :user do
    name                  "Michael Hartl"
    email                 "mhartl@example.com"
    password              "foobar"
    password_confirmation "foobar"
  end
end

then call it from your users controller specs as:

FactoryGirl.create(:user)

I got this exact same error message. I just restarted my Spork server and Autotest and everything went green for me.

In your spec use

  @user = FactoryGirl(:user)

instead of

  @user = Factory(:user)

I had this problem, but it was because I had placed the factory girl gem under the development section instead of the test section of the Gemfile. Once under the test section, it worked. One difference I note between my entry and yours is that mine specifies 1.0:

group :test do
  gem 'rspec-rails', '2.6.1'
  gem 'webrat', '0.7.1'
  gem 'factory_girl_rails', '1.0'
end

For me I had to add require 'factory_girl' to test_helper.rb

My solution: I've accidentally included it in the :development block, and simply had to move it to the :test block

(I've listed it here, because it might help someone who doesn't follow the tutorial correctly)

I have done so, add require 'factory_girl' to test_helper.rb and

@user = FactoryGirl.create(:user)

For those finding this page now: note where you once used "FactoryGirl" you must now use "FactoryBot" in your tests. From the thoughtbot announcement page:

"We’re renaming factory_girl to factory_bot (and factory_girl_rails to factory_bot_rails). All the same functionality of factory_girl, now under a different name."

More details here:

https://robots.thoughtbot.com/factory_bot

I was determined to use the newest version of Factory Girl, so I tried to adapt the code. Didn't work for me, so I used

gem 'factory_girl_rails', '1.0'

in the Gemfile to lock the version at 1.0

bundle update

restart spork and autotest and it worked.

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