factory girl error - ruby-on-rails-3

I am getting an error when I'm running my test file.
factory.rb:334:in `factory_by_name': No such factory: user (ArgumentError)
I have the user model but still why am getting this error?
My factories.rb contains:
FactoryGirl.define do
factory :user do |u|
u.sequence(:email) {|n| "#{n}#email.com"}
u.login 'Joe'
u.password 'password'
u.password_confirmation 'password'
u.phone '1111111111'
u.gender 'F'
u.active '1'
u.social_profile_active '1'
end
end
in test_helper.rb
ENV["RAILS_ENV"] = "test"
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
require 'factory_girl'
#Factory.find_definitions
class ActiveSupport::TestCase
# Setup all fixtures in test/fixtures/*.(yml|csv) for all tests in alphabetical order.
#
# Note: You'll currently still have to declare fixtures explicitly in integration tests
# -- they do not yet inherit this setting
#fixtures :all
# Add more helper methods to be used by all tests here...
end
my ruby version is 1.8.7 and rails3.0.1
And my gemfile looks like this:
group :test do
gem 'shoulda'
gem 'factory_girl_rails'
gem 'mocha'
end

Rename your directory to one of the following:
Factories can be defined anywhere, but will be automatically loaded if
they are defined in files at the following locations:
test/factories.rb
spec/factories.rb
test/factories/*.rb
spec/factories/*.rb
https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md

Related

NoMethodError: Undefined method `failure_message` - Shoulda

I am trying to use Shoulda to test my user class as followed:
user_test.rb
require 'test_helper'
include Devise::TestHelpers
class UserTest < Test::Unit::TestCase
should have_many(:holidays)
should have_many(:hopsital_bookings)
should have_and_belong_to_many(:roles)
should belong_to(:hospital)
end
User.rb
belongs_to :hospital
belongs_to :department
has_many :holidays
has_many :hospital_bookings
has_and_belongs_to_many :roles
When I run rake test I get the following output: Imgur.
Any ideas what I am missing here and why this is not working because it should!
It seems that you have to:
1) Put at your gem file:
group :test do
gem 'shoulda'
end
2) run bundle install

Organizing rspec 2 tests into 'unit' and 'integration' categories in rails

How to organize rspec 2 tests into 'unit' (fast) and 'integration' (slow) categories?
I want to be able to run all unit tests with just rspec command, but not the 'integration' tests.
I want to be able to run only 'integration' tests.
We have groups of the same nature.
We run then one by one both on the local dev boxes and on the CI.
you can simply do
bundle exec rake spec:unit
bundle exec rake spec:integration
bundle exec rake spec:api
This is what our spec.rake looks like
namespace :spec do
RSpec::Core::RakeTask.new(:unit) do |t|
t.pattern = Dir['spec/*/**/*_spec.rb'].reject{ |f| f['/api/v1'] || f['/integration'] }
end
RSpec::Core::RakeTask.new(:api) do |t|
t.pattern = "spec/*/{api/v1}*/**/*_spec.rb"
end
RSpec::Core::RakeTask.new(:integration) do |t|
t.pattern = "spec/integration/**/*_spec.rb"
end
end
One way to do it is to tag your RSpec test cases like this:
it "should do some integration test", :integration => true do
# something
end
When you execute your test cases use this:
rspec . --tag integration
This will execute all the test cases with the tag :integration => true. For more refer to this page.
I had to configure my unit and feature tests as follows:
require 'rspec/rails'
namespace :spec do
RSpec::Core::RakeTask.new(:unit) do |t|
t.pattern = Dir['spec/*/**/*_spec.rb'].reject{ |f| f['/features'] }
end
RSpec::Core::RakeTask.new(:feature) do |t|
t.pattern = "spec/features/**/*_spec.rb"
end
end
Had to add require 'rspec/rails' and change Rspec to RSpec in the answer given by #KensoDev.
Notice at https://github.com/rspec/rspec-rails, they are telling you to place the gem under "group :development, :test" like so,
group :development, :test do
gem 'rspec-rails', '~> 2.0'
end
but if you place this only under :test group only,
group :test do
gem 'rspec-rails', '~> 2.0'
end
then you'll get the above error.
HTH
I suggest to use .rspec file to configure patterns instead of using rake because it's tricky to pass flags to RSpec when using rake.
You can read environment variables in your .rspec file:
<%= if ENV['TEST'] == 'integration' %>
--pattern spec/integration/**/*_spec.rb
<% else %>
<% ENV['TEST'] = 'unit' %>
--pattern spec/unit/**/*_spec.rb
<% end %>
Then you can run TEST=integration rspec to run integration tests or just rspec to run unit tests. The advantage of this approach is that you can still pass flags to it like:
TEST=integration rspec -t login -f doc

devise helper method, confirm! cannot be used/found within factory setup

all,
language: Ruby on rails
version: rails 3
gems in question: devise and factory_girl_rails
I refered to https://github.com/plataformatec/devise/wiki/How-To:-Controllers-and-Views-tests-with-Rails-3-(and-rspec) and tried to set up admin and regular devise users using factory girl for my controller specs. I am using the confirmable module in devise.
In spec/support/controller_macros.rb, I call confirm! after getting a user object from the factory.
The code/comment says
> "user.confirm! # or set a confirmed_at inside the factory. Only
> necessary if you are using the confirmable module"
When I set the value of "confirmed_at" in the users factory, spec/factories/users.rb and run my controller specs (rake spec:controllers), it works BUT when I do not set the value of "confirmed_at" and rely on confirm! in spec/support/controller_macros.rb, it seems that confirm! is not found.
I have even tried putting in " include Devise::TestHelpers" in the
spec/support/controller_macros.rb file but still fails.
The error I got was
Failure/Error: Unable to find matching line from backtrace
NoMethodError:
undefined method `confirm!' for #<User:0x71d9c7901e48>
# ./spec/support/controller_macros.rb:8:in `login_user'
My spec/spec_helper.rb reads as follows.
----------- spec/spec_helper.rb - start ----------------------------
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'webrat'
# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
RSpec.configure do |config|
config.mock_with :rspec
config.include Devise::TestHelpers, :type => :controller
config.extend ControllerMacros, :type => :controller
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
config.fixture_path = "#{::Rails.root}/spec/fixtures"
# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
config.use_transactional_fixtures = true
end
----------- spec/spec_helper.rb - end ----------------------------
What could be wrong that is causing confirm! not to be found/working?
Thank you :)
The confirm! it's just necessary if you are using the :confirmable devise module.
In your user.rb(devise model) put :confirmable in your devise options or if you don't want use this module(this module send a confirmation email to the user.) remove the confirm! from your controller_macros.rb.

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 .

Rails 3 + FactoryGirl: NameError: uninitialized constant Factory

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