I put some code in spec/support/request_helpers.rb
module Requests
module JsonHelpers
def json
#json ||= JSON.parse(response.body)
end
end
end
Then I added config line to spec/rails_helper.rb to access that code from my spec.
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'spec_helper'
require 'rspec/rails'
ActiveRecord::Migration.maintain_test_schema!
RSpec.configure do |config|
config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.use_transactional_fixtures = true
config.infer_spec_type_from_file_location!
config.include Requests::JsonHelpers, :type => :controller
end
So when I run my spec from spec/controller/tasks_controller_spec.rb I get the following error.
/spec/rails_helper.rb:16:in `block in <top (required)>': uninitialized constant Requests (NameError)
How to solve it?
My spec has require 'rails_helper' on the top.
Do you have already added require your support folder?
Add to your spec_helper.rb:
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'spec_helper'
require 'rspec/rails'
# with many helpers
Dir[File.dirname(__FILE__) + "/support/*.rb"].each {|f| require f }
# or only one
# require 'support/request_helpers'
ActiveRecord::Migration.maintain_test_schema!
RSpec.configure do |config|
# some code here
About spec/support
Related
I'm really annoying this problem about this.
Error is like this.
Despite of declaration of TestLoginController, I always trapped same error.
What should I do?
$ bin/rspec
Running via Spring preloader in process 18113
/Users/noriakitakamizawa/dola/spec/controller/test_login_spec.rb:3:in `<top (required)>': uninitialized constant TestLoginController (NameError)
from /Users/noriakitakamizawa/dola/vendor/bundle/ruby/2.3.0/gems/rspec-core-3.5.4/lib/rspec/core/configuration.rb:1435:in `block in load_spec_files'
from /Users/noriakitakamizawa/dola/vendor/bundle/ruby/2.3.0/gems/rspec-core-3.5.4/lib/rspec/core/configuration.rb:1433:in `each'
from /Users/noriakitakamizawa/dola/vendor/bundle/ruby/2.3.0/gems/rspec-core-3.5.4/lib/rspec/core/configuration.rb:1433:in `load_spec_files'
Here's the code.
spec/controller/test_login_spec.rb
require 'rails_helper'
describe TestLoginController do
login_admin
it "should have a current_user" do
# note the fact that you should remove the "validate_session" parameter if this was a scaffold-generated controller
expect(subject.current_user).to_not eq(nil)
end
it "should get index" do
# Note, rails 3.x scaffolding may add lines like get :index, {}, valid_session
# the valid_session overrides the devise login. Remove the valid_session from your specs
get 'index'
response.should be_success
end
end
spec/rails_helper.rb
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'spec_helper'
require 'rspec/rails'
require 'devise'
require 'rspec/autorun'
Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
ActiveRecord::Migration.maintain_test_schema!
RSpec.configure do |config|
config.include Devise::Test::ControllerHelpers, :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
And here's another helper.
spec/spec_helper.rb
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'rspec/autorun'
require 'capybara/rails'
require 'devise'
Rails.logger = Logger.new(STDOUT)
RSpec.configure do |config|
config.include Rails.application.routes.url_helpers
config.include Capybara::DSL
# for Devise
#config.include Devise::TestHelpers, :type => :controller
#config.include Capybara::DSL
config.include Devise::Test::ControllerHelpers, :type => :controller
I am following the rails api book but building the code in an engine. The test is at spec/controllers/concerns/handicap/authenticable_spec.rb and looks like this
require 'spec_helper'
require_relative '../../../../app/controllers/concerns/handicap/authenticable.rb'
class Authentication
include Handicap::Authenticable
end
module Handicap
describe Authenticable, type: :controlller do
let(:authentication) { Authentication.new }
subject { authentication }
describe "#current_user" do
before do
#user = FactoryGirl.create :handicap_user
request.headers["Authorization"] = #user.auth_token
authentication.stub(:request).and_return(request)
end
it "returns the user from the authorization header" do
expect(authentication.current_user.auth_token).to eql #user.auth_token
end
end
end
end
When I run the test directly i.e. rspec ./spec/controllers/concerns/handicap/authenticable_spec.rb I get an error:
uninitialized constant Handicap::FactoryGirl
However, when I run all the tests i.e. rspec spec, it does find the FactoryGirl constant and the test fails with
undefined local variable or method `request' for #<RSpec::ExampleGroups::HandicapAuthenticable::CurrentUser:0x007ff276ad5988>.
According to this github issue, I need to add < ActionController::Base to the Authentication class i.e.
class Authentication < ActionController::Base
but if I add this in, I get
uninitialized constant ActionController
I have also tried adding < Handicap::ApplicationController but get
uninitialized constant Handicap::ApplicationController
There appears to be something wrong with my namespacing. There are three symptoms, the fact that FactoryGirl cannot be found if I run the test by itself, but is found when all the tests are run. The second is that it cannot find ActionController even when all the tests are run. The third is that I need to add the line:
require_relative '../../../../app/controllers/concerns/handicap/authenticable.rb'
to find the module that is being tested.
How do I fix my namespacing?
The rails_helper.rb file is
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../dummy/config/environment.rb', __FILE__)
require 'rspec/rails'
require 'capybara'
require 'capybara/rails'
require 'capybara/rspec'
require 'capybara-screenshot'
require 'capybara-screenshot/rspec'
require 'capybara/poltergeist'
require 'capybara/email/rspec'
require 'pp'
require 'chris_api_helpers'
# Prevent database truncation if the environment is production
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'spec_helper'
require 'rspec/rails'
require 'factory_girl_rails'
ActiveRecord::Migration.maintain_test_schema!
Shoulda::Matchers.configure do |config|
config.integrate do |with|
# Choose a test framework:
with.test_framework :rspec
with.library :rails
end
end
RSpec.configure do |config|
config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.use_transactional_fixtures = true
config.infer_spec_type_from_file_location!
# Filter lines from Rails gems in backtraces.
config.filter_rails_from_backtrace!
# force test migrations for db:migrate
ActiveRecord::Migration.maintain_test_schema!
Capybara::Screenshot.prune_strategy = { keep: 20 }
Capybara::Screenshot.append_timestamp = false
config.include FactoryGirl::Syntax::Methods
FactoryGirl.definition_file_paths << File.join(File.dirname(__FILE__), 'factories')
FactoryGirl.find_definitions
config.include Devise::Test::ControllerHelpers, type: :controller
end
and the spec_helper.rb is
require 'simplecov' if ENV["COVERAGE"]
SimpleCov.start do
add_filter '/spec/'
add_filter '/config/'
add_filter '/lib/'
add_filter '/vendor/'
add_group 'Controllers', 'app/controllers'
add_group 'Models', 'app/models'
add_group 'Helpers', 'app/helpers'
add_group 'Mailers', 'app/mailers'
add_group 'Views', 'app/views'
end if ENV["COVERAGE"]
RSpec.configure do |config|
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end
config.shared_context_metadata_behavior = :apply_to_host_groups
#http://stackoverflow.com/questions/30859037/suppress-backtrace-for-rspec-3
config.backtrace_exclusion_patterns = [
/\/lib\d*\/ruby\//,
/bin\//,
/gems/,
/spec\/spec_helper\.rb/,
/lib\/rspec\/(core|expectations|matchers|mocks)/
]
end
You should not be putting specs into modules. This is the cause of problem here. If you need to reference a namespaced class, reference it like RSpec.describe Handicap::Authenticatable.
In general, when you are within a namespace and need to reference something explicitly from the 'root' scope, you can prepend it with double-colons. Such as:
module Handicap
class Something
def do_stuff
::FactoryGirl.create(:person)
end
end
end
It turns out that at the top of my file I should have had require 'rails_helper', not require 'spec_helper'``. All my other files hadrequire 'rails_helper'`` so when I ran the whole test suite, the rails_helper was being loaded anyway.
Embarrassing, but this Q&A might help someone else that has trouble spotting simple errors.
I try to test the login methods for sorcery gem and i get an error.
I user factory girl for factories in my rspec tests.
All i want to do is to add a before method that logs me in, and after that i want to test the actions for my controller.
My spec_helper.rb
require 'factory_girl'
require_relative '../spec/factories/blog.rb'
require_relative '../spec/factories/user.rb'
require_relative '../spec/factories/category.rb'
RSpec.configure do |config|
config.include FactoryGirl::Syntax::Methods
config.include Sorcery::TestHelpers::Rails::Controller, type: :controller
config.include Sorcery::TestHelpers::Rails::Integration, type: :feature
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end
end
my rails_helper.rb
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'spec_helper'
require 'rspec/rails'
RSpec.configure do |config|
config.infer_spec_type_from_file_location!
config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.use_transactional_fixtures = true
end
the error i get when i run my rspec
Running: spec
/home/user/work/project_name/spec/spec_helper.rb:9:in `block in <top (required)>': uninitialized constant Sorcery::TestHelpers::Rails::Controller (NameError)
My work environment:
Rails 3.2, Ruby 1.9.3, rspec - rails 3.3, sorcery 0.8.2
I found the problem after hours of pain.
The problem was that for sorcery version 0.8.2 you need to add to spec_helper.rb the following code:
RSpec.configure do |config|
.................................(other stuff)
config.include Sorcery::TestHelpers::Rails
..........................(other stuff)
end
and after that use in your specs
#user = User.create
login_user(#user)
I'm trying to include additional Devise helpers in Rspec but am receiving the following error:
rails_helper.rb:56:in `block in <top (required)>': uninitialized constant ControllerMacros (NameError)
Line 56 in rails_helpers.rb is the config.include ControllerMacros line that I have. I've tried to solve this with the solutions posted in other SO posts but can't seem to get this to work. I understand this might be a require order issue but haven't been able to sort out the right order.
rails_helper.rb
ENV["RAILS_ENV"] ||= 'test'
require 'spec_helper'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'capybara/rails'
require 'capybara/rspec'
require 'devise'
ctiveRecord::Migration.maintain_test_schema!
RSpec.configure do |config|
config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.use_transactional_fixtures = true
config.infer_spec_type_from_file_location!
config.include Capybara::DSL
config.include Devise::TestHelpers, :type => :controller
config.include ControllerMacros, :type => :controller
end
spec/support/controller_macros.rb
module ControllerMacros
def login_business
before(:each) do
#request.env["devise.mapping"] = Devise.mappings[:business]
business = FactoryGirl.create(:business)
buisness.confirm!
sign_in business
end
end
end
spec/business_account_controller_spec.rb
require 'spec_helper'
require 'rails_helper'
describe BusinessAccountController do
login_business
it "should have current user" do
expect(subject).to_not be_nil
end
end
You need to require it in your rails_helper. I place all of my modules in /spec/support and then put Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f } at the top of my rails_helper
It's weird issue, zeus start running smoothly.
rspec spec/ does it's job flawless.
My spec_helper config is
# encoding: UTF-8
require 'rubygems'
# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'email_spec'
require 'rspec/autorun'
require 'capybara/rspec'
require 'shoulda-matchers'
require 'shoulda/matchers/integrations/rspec'
Dir["./spec/support/**/*.rb"].sort.each {|f| require f}
RSpec.configure do |config|
config.include FactoryGirl::Syntax::Methods
config.include Devise::TestHelpers, type: :controller
config.include Capybara::DSL, type: :request
config.treat_symbols_as_metadata_keys_with_true_values = true
config.mock_with :rspec
config.use_transactional_fixtures = true
end
I have shared contexts in spec/support/shared_contexts.rb (which is normally included). rspec spec/ passed all tests, then zeus rspec spec/ passed all tests and throws inclusion errors like this
`find_and_eval_shared': Could not find shared context "with signed user" (ArgumentError)
It tries to pass zeus rspec spec/models and then throws 'factory_girl' inclusion errors while rspec spec/models do it's job fine.
It appears to look like this issue https://github.com/burke/zeus/issues/175
I found this behavior was cause by
require 'rspec/autotest'
in spec_helper.rb