unitialized constant Rspec (Name Error) on Rspec.describe - ruby-on-rails

When I run my tests, I get this error:
top (required) : uninitialized constant Rspec (NameError)
This is the model test that fails, unless I remove 'Rspec.'
ROOT_APP/spec/models/document/date_spec.rb:
require 'rails_helper'
Rspec.describe Document::Date, :type => :model do
pending "add some examples to (or delete) #{__FILE__}"
end
I understand that it is better to use Rspec.describe instead of describe. (something about monkey patching, not really sure what this is).
Of course I could just use describe by itself, which is what I'm doing now just to make my tests work. I just want to know more about what may be happening.
All under the ROOT_APP/spec directory:
rails_helper.rb
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'spec_helper'
require 'factory_girl'
require 'capybara/rspec'
require 'capybara/rails'
Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }
RSpec.configure do |config|
config.infer_spec_type_from_file_location!
config.include(MailerMacros)
config.before(:each) { reset_email }
config.filter_run :focus => true
config.run_all_when_everything_filtered = true
config.include FactoryGirl::Syntax::Methods
end
spec_helper.rb
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
end
I tried putting the spec_helper code into the rails_helper.rb file so there's only one file and I get the same error.
Thank you for any answers/advice.

You have a typo :
RSpec.describe Document::Date, :type => :model do
pending "add some examples to (or delete) #{__FILE__}"
end
It is RSpec, not Rspec. Note the upper case S.

Related

Rails 5.1: Rspec can't see Capybara features

I have some feature specs in my project that look roughly like this:
# specs/features/canvas_integration.rb
require 'spec_helper'
feature 'Routes to default page' do
let!(:mode) { create(:mode) }
scenario 'as anyone' do
visit root_path
expect(page).to have_content('Your home')
end
end
But running the specs results in nothing:
rspec spec/features
No examples found.
My spec_helper.rb looks like this:
# frozen_string_literal: true
require 'simplecov'
SimpleCov.start 'rails'
require File.expand_path('../../config/environment', __FILE__)
require 'codeclimate-test-reporter'
require 'rspec/rails'
require 'webmock/rspec'
require 'devise'
require 'codeship'
require 'capybara/rspec'
require 'capybara/rails'
WebMock.disable_net_connect!(allow_localhost: true)
Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
RSpec.configure do |config|
config.include Devise::Test::ControllerHelpers, type: :controller
config.include Devise::Test::ControllerHelpers, type: :view
config.include FactoryGirl::Syntax::Methods
config.extend ControllerMacros, type: :controller
config.include Macros
config.color = true
config.fixture_path = "#{::Rails.root}/spec/factories/fixtures"
config.infer_spec_type_from_file_location!
config.infer_base_class_for_anonymous_controllers = false
config.order = 'random'
config.warnings = false
config.default_formatter = 'doc' if config.files_to_run.one?
config.profile_examples = 10
config.use_transactional_examples = false
config.use_transactional_fixtures = false
config.before(:suite) do
DatabaseCleaner.strategy = :transaction
DatabaseCleaner.clean_with(:truncation)
end
# config.before(:each, type: :system) { driven_by :rack_test }
config.mock_with :rspec do |mocks|
mocks.verify_doubled_constant_names = true
end
config.expect_with :rspec do |c|
c.syntax = :expect
end
end
Why can't Rspec find my features?
Your files need to end in _spec.rb in order for RSpec to load them when specifying a directory. So rename to specs/features/canvas_integration_spec.rb
Also note that in Rails 5.1 database cleaner is probably not necessary (if you're using one of the usual databases) - so you should be able to remove/comment out that and re-enable transactional testing. Additionally use_transactional_examples is an alias of use_transactional_fixtures so specifying both doesn't make sense.
I think your test spec filename should be specs/features/canvas_integration_spec.rb instead of specs/features/canvas_integration.rb
Why?
The files read by the rspec-rails gem are those that end in _spec.rb

Requiring module in Rspec in rails 4 application

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

rspec + capybara + factory_girl always creating test user

I have an odd problem and I'm not sure how to debug it. I'm currently using these gems (which are the latest versions as of this post):
factory_girl-4.5.0
rspec-rails-3.1.0
capybara-2.4.4
guard-2.6.1
Whenever I start guard using bundle exec guard or whenever a new test runs, it always create a user in the test database. So that User.count == 1 at every start. I can't figure out where that's called.
Here's my spec_helper.rb:
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'email_spec'
# require 'rspec/autorun'
require 'capybara/rspec'
require 'factory_girl'
require 'lorem-ipsum'
# 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.include(EmailSpec::Helpers)
config.include(EmailSpec::Matchers)
config.include FactoryGirl::Syntax::Methods
config.include ApplicationHelper
config.use_transactional_fixtures = false
config.infer_base_class_for_anonymous_controllers = false
config.include RSpec::Rails::RequestExampleGroup, type: :feature
config.infer_spec_type_from_file_location!
config.include Requests::JsonHelpers, :type => :request
config.order = "random"
config.before(:suite) do
DatabaseCleaner.strategy = :truncation
Capybara.javascript_driver = :webkit
end
config.before(:each) do
Mongoid::IdentityMap.clear #If you have the identity map enabled in your application, you should set up a global hook to clear out the map before each test so the test suite does not create memory bloat. For example in RSpec in spec_helper.rb.
Rails.cache.clear
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
end
and my factories.rb is pretty simple:
FactoryGirl.define do
factory :user, aliases: [:authored_by] do
sequence(:first_name) {|n| "TestFN#{n}" }
sequence(:last_name) {|n| "TestLN#{n}" }
sequence(:email) {|n| "rspec-test-#{n}#example.com" }
end
end
Any idea on where I should start debugging to figure out why the user is being created?
Look in your /spec directory. Is FactoryGirl.lint being called? Are you calling the user factory in a test defined in spec/features, etc? Are you using DatabaseCleaner to maintain your test environment?

FactoryGirl objects not being dropped after tests. Please review my test setup

Objects are persisting after tests run. I confirmed by doing a PowerUp.all.count test and the count increases by 2 on each run, which a number equal to the objects created for the test on each run. I don't know if I'm misusing FactoryGirl, or if I have a misconfigured spec_helper.
spec/support/factory_girl.rb:
RSpec.configure do |config|
config.include FactoryGirl::Syntax::Methods
end
spec/rails_helper.rb:
ENV["RAILS_ENV"] ||= 'test'
require 'spec_helper'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }
ActiveRecord::Migration.maintain_test_schema!
RSpec.configure do |config|
config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.use_transactional_fixtures = false
config.infer_base_class_for_anonymous_controllers = false
config.infer_spec_type_from_file_location!
end
spec/spec_helper.rb:
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'factory_girl'
RSpec.configure do |config|
config.order = :random
config.before(:all) do
FactoryGirl.reload
end
Kernel.srand config.seed
config.expect_with :rspec do |expectations|
expectations.syntax = :expect
end
config.mock_with :rspec do |mocks|
mocks.syntax = :expect
mocks.verify_partial_doubles = true
end
end
spec/api/power_up_spec.rb:
describe Api::PowerUpsController, :type => :controller do
describe "GET power_ups" do
it "returns all power-ups" do
FactoryGirl.create :power_up, name: "Increase rate of take", description: "You gain points more quickly"
FactoryGirl.create :power_up, name: "Decrease rate of give", description: "You lose points more slowly"
get :index, :format => :json
expect(response.status).to eq 200
body = JSON.parse(response.body)
power_up_names = body.map { |m| m["name"] }
expect(power_up_names).to match_array(["Increase rate of take",
"Decrease rate of give"])
end
end
end
config.use_transactional_fixtures = false
This turns off the default behavior, which is to rollback transactions after each example. When set to false RSpec does not attempt to manage the test database.
You can use database_cleaner to remove the rows created by tests when RSpec is not using transactions. This is often used when writing feature specs.

Capybara methods are undefined

I cannot get capybara to work. I am using capybara 2.0.0
I get this error
Failure/Error: visit "/users/sign_in"
NoMethodError:
undefined method `visit' for #<RSpec::Core::ExampleGroup::Nested_21:0x007fdda4c6eba0>
on this spec
spec/requests/forgot_password_spec.rb
describe "forgot password" do
it "redirects user to users firms subdomain" do
visit "/users/sign_in"
end
end
I do not get any errors that it cannot find capybara and it's included in the spec_helper.rb
spec_helper.rb
require 'rubygems'
require 'spork'
require 'database_cleaner'
Spork.prefork do
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'capybara/rspec'
require 'rspec/autorun'
require 'factory_girl'
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
RSpec.configure do |config|
config.include Devise::TestHelpers, :type => :controller
config.extend ControllerMacros, :type => :controller
config.include RequestMacros, :type => :request
config.mock_with :rspec
config.use_transactional_fixtures = false
config.before(:suite) do
DatabaseCleaner.strategy = :truncation
end
config.before(:each) do
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
config.infer_base_class_for_anonymous_controllers = false
end
Spork.each_run do
FactoryGirl.reload
end
end
Has anybody else encountered this?
If you've got version >= 2.0, any tests that use Capybara methods like visit should go under a spec/features directory, and not under spec/requests, where they'd normally reside in Capybara 1.1.2.
Have a look at the following links for more information:
rspec-rails and capybara 2.0: what you need to know
rspec-rails gem Capybara page
If you don't want to use a spec/features directory, you should be able to mark a test as a feature in the following way and have Capybara methods work:
describe "Some action", type: :feature do
before do
visit "/users/sign_in"
# ...
end
# ...
end
In my case, I got this error because I forgot to putrequire "spec_helper"
at the top of my new spec file.
I've done it enough times that I'm adding an answer to an already answered question in hopes that it helps some other knucklehead (or most likely me searching this again in the future).

Resources