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.
Related
I was unable to run my rails server in development mode. I have installed two gems are resque and resque-scheduler into rails application. I have searched for the solution online but still, I was struggling with it.
Gemfile:
gem 'resque'
gem 'resque-scheduler'
Config file of application:
config.active_job.queue_adapter = :resque
The resque.rake file:
require 'resque/tasks'
require 'resque/scheduler/tasks'
namespace :resque do
puts "Loading Rails environment for Resque"
task :setup do
require 'resque'
require 'resque-scheduler'
Resque.redis = 'localhost:6379'
end
end
I have a Rails 3 app that I am turning into a Rails engine / gem.
This engine has some gem dependencies that I have put inside it's .gemspec file.
I have created a new 'parent' Rails 3 app, and I would like to add my engine gem to the Gemfile and have the gem's dependencies automatically 'loaded', but this does not work for me! bundle install installs the gem dependencies fine, but when I start the server, the app crashes because they are not loaded.
For example, my engine's gemspec contains these lines:
s.add_runtime_dependency(%q<rails>, ["= 3.0.7"])
s.add_runtime_dependency(%q<acts_as_commentable>, [">= 3.0.1"])
s.add_runtime_dependency(%q<haml>, [">= 3.1.1"])
.. and the parent Rails 3 application has these lines in its Gemfile:
source 'http://rubygems.org'
gem 'my_engine', :path => "~/src/gems/my_engine"
But I get the following error:
undefined local variable or method `acts_as_commentable'
from /home/user/src/gems/my_engine/app/models/account.rb:66:in `<class:Account>'
But if I add gem 'acts_as_commentable', '>= 3.0.1' to the Gemfile of the parent Rails 3 app, then the gem is loaded and the error disappears.
I am using Rails 3.0.8.
Does anyone have any suggestions? Do I need to change something about the way my engine is loading?
During main Rails app boot, Bundler will only require dependencies directly listed in the Gemfile but not any sub-dependencies. It's your library's/Engine's responsibility to require its dependencies when it itself gets required. You can do so using initializers in your Railtie.
class MyRailtie < Rails::Railtie
initializer "require stuff" do
require "stuff"
end
end
In our Rails Engine we used a small trick to require dependencies automatically. Unfortunately you can't specify whether or not they should load in the .gemspec, which would allow for greater control.
Gem.loaded_specs["our_rails_engine"].dependencies.each do |d|
begin
require d.name
rescue LoadError => le
# Put exceptions here.
raise le if d.name !~ /factory_girl_rails/
end
end
I'm looking at Spree (the superhero of Rails Engines!), and they do this in spree_core-0.60.1/lib/spree_core.rb:
require "rails/all"
require 'state_machine'
require 'paperclip'
require 'stringex'
require 'will_paginate'
require 'nested_set'
require 'acts_as_list'
require 'resource_controller'
require 'active_merchant'
require "meta_search"
require "find_by_param"
So the answer is that within your gem, you have to require all of it's gem dependencies one by one. Well, that's how I will do it for now. But please comment if this ever changes in the future.
Seems it don't work, i create a host project and a sub-project with rails 3 engine.
Added the gem to engine's gemspec
s.add_dependency 'simple_form'
then added the require to engine_name.rb like below
require 'simple_form'
But if delete the line [gem 'simple_form'] in host project's Gemfile, it will show undefined immediatly
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 .
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
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