Rails 3 + FactoryGirl: NameError: uninitialized constant Factory - ruby-on-rails-3

ruby-1.9.2-p180 :007 > Factory.define :user do |user|
ruby-1.9.2-p180 :008 > user.email "user#example.com"
ruby-1.9.2-p180 :009?> user.password "foobar"
ruby-1.9.2-p180 :010?> user.password_confirmation "foobar"
ruby-1.9.2-p180 :011?> end
NameError: uninitialized constant Factory
My Gemfile:
group :test do
gem "rspec-rails"
gem 'webrat', '0.7.1'
gem 'spork', '0.9.0.rc4'
gem 'factory_girl_rails'
end
Even tough it seems I have everything as it should, I keep getting that error. I also have factories.rb created.
Thanks

I suppose you try in console in development environment. But you add the Factory gem only in test environment.
If you want access to Factory_girl in development use in your Gemfile :
group :test, :development do
gem 'factory_girl_rails'
end
Or if you want test your Factory launch your console in test environment :
rails c test

We had a similar problem on our end, rake spec seemed to be randomly failing with the error uninitialized constant FactoryGirl. The error was random -> coming and going. We went back half a dozen git commits to try and resolve it. In the end it was a silly mistake.
The fundamental problem is RAILS_ENV is set to development. It needs to be set to test when you run rake spec.
Address by:
Making certain that we are running rake spec in the RAILS_ENV test environment and its exported/sourced properly. To never confuse our environemnts, we modified zsh $RPROMPT env variable to show the current env.
export RPROMPT="[%{$fg_no_bold[yellow]%}$RAILS_ENV%{$reset_color%}]"
Require FactoryGirl in the spec ruby files gave a much better error message. At least rspec would run vs just fail outright this way when the environment was wrong. We also updated our gemfile to make sure factory_girl_rails and factory_girl were loaded both for development and testing.
Now we just run rpsec using the gem guard in a dedicated terminal with the proper RAILS_ENV set.
Its one of those gotchas.
We're running Ruby 1.9.3, Rails 3.2.9, Rspec 2.12, factory_girl 4.1.

I also ran into this while I was doing the Hartl tutorial.
If you are using "Spork" to speed up your tests and it is running in the background when you add the FactoryGirl code, you will need to stop it and restart it.

You should also change Factory.define to FactoryGirl.define, like in this example
FactoryGirl.define do
factory :user do
name 'John Doe'
date_of_birth { 21.years.ago }
end
end
from the factory_girl documentation

Related

Rails Mocha gem - NoMethodError: undefined method `any_instance'

I'm using the Mocha gem in a Rails project to make stubs and bypass some live API calls.
I'm conforming to the documentation but keep getting an error.
In Gemfile (I use Bundler) I have:
gem 'minitest'
gem 'minitest-rails'
gem 'mocha', :require => false
In test_helper.rb:
require 'minitest'
require 'mocha/mini_test' # This is the last require statement
In product_controller_test.rb:
require 'test_helper'
class ProductControllerTest < ActionController::TestCase
setup do
Product.any_instance.stubs({
manufacturer: "Acme"
})
end
end
The output is always NoMethodError: undefined method 'any_instance' for #<Class:blah>.
I have another Rails project where I can use any_instance successfully, so I've tried resolving by replicating the gems, require statements, etc. but with no success. I've also tried different permutations like require 'minitest/autorun', require "minitest/rails', and require 'mocha/setup'/require 'mocha', etc.
I'm on Rails 4.1.1 and using MiniTest 5.3.3 and Mocha 1.0.0.

ruby-ldap gem not work in rails3 app, but work in rails console

I want to build a rails3 website authed with LDAP, so I chose ruby-ldap gem (not net/ldap) which we used in our old rails2 apps and works very well.
But I keep on getting weird error in rails3 app, See the codes below:
require 'ldap'
class WelcomeController < ApplicationController
def index
begin
#test = LDAP::Conn.new('10.72.64.11', 389)
rescue LDAP::Error
p LDAP::Error
end
render :text => "ok"
end
end
welcome#index is my root route. Most time, the app crashes when going to LDAP::Conn.new('10.72.64.11', 389), even I tried to use "pry" to debug and track, throwing
[1] 24797 trace trap rails s
and the WEBrick server will be terminated right that time.
Sometimes it throws another type error when I use "pry" to step,
#<NameError: uninitialized constant WelcomeController::LDAP>
While try it in the console, everything goes well.
1.9.3-p194 :001 > require 'ldap'
=> true
1.9.3-p194 :002 > #test = LDAP::Conn.new('10.72.64.11', 389)
=> #<LDAP::Conn:0x00000101289568>
1.9.3-p194 :003 >
Can you guide me out of this crazy stuff? I am using ruby 1.9.3p194 and rails 3.2.8
A few months later, I kind of figure out what the problem is...
The ruby-ldap gem has problem on running on the rails default server: Webrick.
Try Pow or Passenger, it works perfect!
After reading this page: http://www.ruby-forum.com/topic/62920
I tried moving the require 'ldap' from the controller or model file, and into the very top line of my environment file (xxxlocal.rb)
After I did that, I was able to run it ok in webrick also.

rspec returns "PG::Error: ERROR: relation "table_name" does not exist"

Environment is REE(2011.12) on rvm, rspec 2.8.0, rails 3.0.6, and pg 0.13.2. Using PostgreSQL 8.3.17 on CentOS 5.6. The db:migrate have work correctly. But rspec have got following error.
1) ApiController articles OK
Failure/Error: Unable to find matching line from backtrace
ActiveRecord::StatementInvalid:
PG::Error: ERROR: relation "table_name" does not exist
: DELETE FROM "table_name"
I'm updating my project from rails 2.3.5 with rspec 1.x series to rails 3.0 with rspec2. Copied all rspec tests, and I have merged old spec_helper.rb and new one(It was generated rails g rspec:install).
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'rspec/autorun'
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
RSpec.configure do |config|
config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.use_transactional_fixtures = true
end
I read similar question about this error.So I tried rake db:test:prepare or rake db:test:load, But It's not resolve. Do you have any idea?
It looks like the test hasn't run on test database... How do I do? :(
I've run into this in two instances (updated 6/13/2012):
First:
I haven't yet migrated my test database...
rake db:migrate
...which you need to do before both db:test:prepare and db:test:load.
When you invoke rspec it should prepare and load your database for you anyway. You shouldn't have to do that by hand.
Second:
A typo in my migration. I accidentally reversed my table and column names in the parameter list.
A migration on a Rails 3.1 project:
def change
add_column :had_import_errors, :studies, :boolean, :default => false
add_column :import_data_cache, :studies, :text
end
...which is wrong, because has_import_errors and import_data_cache are my column names, and they therefore should come second, not first.
The correct migration, with the table name first was:
def change
add_column :studies, :had_import_errors, :boolean, :default => false
add_column :studies, :import_data_cache, :text
end
This usually happens when you have rspec running while migrating (usually via guard). A simple solution is to quit guard, do the migration and restart guard.
It typically indicates that there is another open PostgreSql connection. To bubble up the right error try % rake db:test:prepare
Running test prepare showed the following below and when the open connection (PGAdmin in my case) was closed the issue was resolved.
rake aborted!
PG::Error: ERROR: database "xyz_test" is being accessed by other users
DETAIL: There are 1 other session(s) using the database.
: DROP DATABASE IF EXISTS "xyz_test"
Tasks: TOP => db:test:load => db:test:purge
(See full trace by running task with --trace)
Just hit this same error, nothing worked but dropping and re-creating the database, this fixed it for me.
rake db:drop db:create db:migrate

ruby resque without loading rails environment

I have a resque worker which works great but is just too slow. The main reason for this is I'm using activerecord and having to load the entire environment which takes at least 10-20 seconds just to load up (I don't keep a running worker at all times as I'm using Heroku and pay for the time the worker runs). I'm using a resque worker to grab & parse data from an external website and then dumping the data into my database.
My question is whether I should rewrite the method to not use Rails and instead use DataMapper? Or something else which would load faster than activerecord.
Or If I should extract the code (using ActiveRecord) which figures out what to do with the external data and move it out of the worker and back into the app?
Hope that makes sense.
I have the same problem.
you could setup your environment on the rake resque:setup rake task
I tried this. assuming my rake resque task is on lib/tasks/resque.rake
require "resque/tasks"
task "resque:setup" do
root_path = "#{File.dirname(__FILE__)}/../.."
db_config = YAML::load(File.open(File.join(root_path,'config','database.yml')))["development"]
ActiveRecord::Base.establish_connection(db_config)
require "#{root_path}/app/workers/photo_downloader.rb" #workers
#Dir.glob("#{root_path}/app/models/*").each { |r| puts r; require r } #require all model
require "#{root_path}/app/models/photo.rb" # require model individually
end
I haven't completely success beacuse I use the Paperclip gem which require rails environment
Rails’ bootstrap is really slow; it is intended to be kept running, until certain time for restart (to eliminate some memory leaks there most likely is, any software is not bug-free), and is not intended to be used as a site that is launched for one request and then shut down.
That kind of usage more resembles a script. If you need to launch it with browser, you can easily use something like Erubis to write the page and use ActiveRecord in the script (I think it was useable outside of rails) or similar abstraction layer. Myself, for small tasks, I just use Mysql2.
Use bundler to get active_record and other gem to you without rails application .
require 'rubygems'
require 'logger'
require 'active_record'
require 'bundler'
require "active_support"
require "spreadsheet"
require 'net/ping'
require 'net/http'
Bundler.setup
Bundler.require(:default) if defined?(Bundler)
$config_logger = Logger.new("./log/dev.log")
class Dbconnect
def initialize
#settings = YAML.load_file('./config/database.yml')["development"]
#adapter = #settings["adapter"] if #settings["adapter"]
#database = #settings["database"] if #settings["database"]
#pool = #settings["pool"] if #settings["pool"]
#timeout = #settings["timeout"] if #settings["timeout"]
end
def connect_to_db
ActiveRecord::Base.establish_connection(
:adapter => #adapter,
:database => #database,
:reconnect => #reconnect,
:pool => #pool,
:timeout => #timeout)
$config_logger.info "\n db Connected: to => #{#database} "
end
end
end
}
Example Gemfile :
source "http://rubygems.org"
gem 'mail'
gem "escape_utils"
gem 'json',:require => "json"
gem 'json_pure'
gem 'resque'
gem 'resque-scheduler'
gem 'redis-namespace'
gem 'resque-status'
gem 'rake'
gem 'em-udns'
gem 'sqlite3'
gem 'spreadsheet'
gem 'activerecord', '3.2.1', :require => "active_record"
gem 'net-scp', :require => 'net/scp'
gem 'net-sftp', :require => 'net/sftp'
gem 'net-ssh', :require => 'net/ssh'
gem 'dir'
gem 'amatch'
gem 'haml'
gem 'net-ping'
gem install bundler
rest of the thing : bundle install .

Webmock gem in rails 3 and properly including it

I'm likely doing something very simply wrong, but I'm not quite sure what it is. I am porting a rails 2 application to rails 3. This application uses webmock for a bunch of it's tests.
If I include
gem 'webmock'
In my Gemfile, the tests pass, but when I start the server and run the app locally, hitting a controller that should make a web call throws an error:
WebMock::NetConnectNotAllowedError
If I do NOT include the line in my Gemfile, then when I run the app locally, it works fine, but the tests error out with:
`require': no such file to load -- webmock (LoadError)
When this line is hit in my test_helper.rb
require 'webmock'
I'm guessing I've got something configured wrong, but I haven't hit the right google incantation to shed any light on it yet. Where I did I go astray?
Thank you.
Try telling your Gemfile to only load webmock when you're in a test environment:
group :test do
gem "webmock"
end
On my Ruby 1.9 Rails 3 instance I have something like the following:
group :test do
gem "mocha"
gem "webmock"
end
group :development do
gem 'ruby-debug19', :require => 'ruby-debug'
end