I read tutorial from How-To:-Stub-authentication-in-controller-specs
And try to write some code but it didn't work. Can anybody help me to understand? Thank you
spec/support/authen_helper.rb
module AuthenHelper
def sign_in(user = double('user'))
if user.nil?
allow(request.env['warden']).to receive(:authenticate!).and_throw(:warden, {:scope => :user})
allow(controller).to receive(:current_user).and_return(nil)
else
allow(request.env['warden']).to receive(:authenticate!).and_return(user)
allow(controller).to receive(:current_user).and_return(user)
end
end
def sign_in_as_admin(user = double('user'))
allow(user).to receive(:role?).with('admin').and_return(true)
allow(request.env['warden']).to receive(:authenticate!).and_return(user)
allow(controller).to receive(:current_user).and_return(user)
end
end
rails_helper.rb
ENV["RAILS_ENV"] ||= 'test'
require 'spec_helper'
require File.expand_path("../../config/environment", __FILE__)
ActiveRecord::Migration.maintain_test_schema!
RSpec.configure do |config|
config.fixture_path = "#{::Rails.root}/spec/fixtures"
end
spec_helper.rb
require 'rubygems'
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.expect_with :rspec
config.mock_with :rspec
config.filter_run :focus
config.run_all_when_everything_filtered = true
config.order = :random
config.color = true
config.use_transactional_fixtures = false
config.infer_spec_type_from_file_location!
config.include AuthenHelper, :type => :controller
end
spec/controllers/api/v1/user_controller_spec.rb
require 'rails_helper'
module API
module V1
describe User, :type => :controller do
sign_in
end
end
end
Error:
undefined local variable or method `sign_in' for RSpec::ExampleGroups::APIV1User:Class (NameError)
You should write the test inside an it block:
describe User, :type => :controller do
it 'signs in' do
sign_in
end
end
If you want to do this before any test, you should do it inside a before block:
describe User, :type => :controller do
before(:each) do
sign_in
end
end
Related
I have written tests on Rspec for my model User and get error while starting 'rspec spec'
NameError: uninitialized constant User
my test spec/models/ivd/user_spec.rb
require 'rails_helper'
module Ivd
RSpec.describe User, type: :model do
let(:user) { FactoryGirl.create(:ivd_user, email: "user#example.org", password: "very-secret", admin: true) }
it 'has a valid factory' do
expect(user).to be_valid
end
describe '.find_for_oauth' do
let!(:user) { FactoryGirl.create(:ivd_user) }
describe 'twitter' do
let(:auth) { OmniAuth::AuthHash.new({provider: 'twitter', uid: '12345'})}
context 'user has already authorization' do
it 'return user' do
user.identities.create({provider: 'twitter', uid: '12345'})
expect(User.find_for_oauth(auth)).to eq user
end
end
end
end
end
end
spec_helper.rb
ENV['RAILS_ENV'] ||= 'test'
require 'simplecov'
# SimpleCov.formatter = SimpleCov::Formatter::HTMLFormatter
SimpleCov.start :rails do
add_filter do |source_file|
source_file.lines.count < 5
end
end
require File.expand_path('../dummy/config/environment.rb', __FILE__)
require 'rspec/rails'
require 'rspec/autorun'
require 'factory_girl_rails'
require 'capybara/poltergeist'
# require 'capybara/rails'
require 'ivd/seeder'
# http://www.thegreatcodeadventure.com/stubbing-with-vcr/
require 'vcr'
require 'webmock/rspec'
WebMock.disable_net_connect!(allow_localhost: true)
# load(Rails.root.join("db", "seeds.rb"))
# Configure capybara for integration testing
# Capybara.default_driver = :rack_test
# Capybara.default_selector = :css
# js_options = {js_errors: false}
# above is sometimes useful to troubleshoot errors with tests
js_options = {}
Capybara.register_driver :poltergeist do |app|
Capybara::Poltergeist::Driver.new(app, js_options)
end
Capybara.javascript_driver = :poltergeist
# Capybara.ignore_hidden_elements = false
# http://stackoverflow.com/questions/24078768/argumenterror-factory-not-registered
# as per above, need to explicitly set below
FactoryGirl.definition_file_paths = [File.expand_path('../factories', __FILE__)]
FactoryGirl.find_definitions
# Oddly above does not occur if factory_girl_rails is only referrenced in ivd.gemspec
# but not main gemfile
Rails.backtrace_cleaner.remove_silencers!
# Load support files
Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f }
ActionController::Base.prepend_view_path "#{Ivd::Engine.root}/app/themes/default/views/"
RSpec.configure do |config|
# TODO - consider precompiling assets to speed up tests
# config.before(:suite) do
# Rails.application.load_tasks
# Rake::Task["assets:precompile"].invoke
# end
config.include JsonSpec::Helpers
config.warnings = false
config.mock_with :rspec
config.infer_base_class_for_anonymous_controllers = false
config.order = 'random'
# config.include Ivd::ApplicationHelper
# config.include Rails.application.routes.url_helpers
# config.include Ivd::Engine.routes.url_helpers
config.use_transactional_fixtures = false
#
# Make sure the database is clean and ready for test
config.before(:suite) do
DatabaseCleaner.clean_with(:truncation)
Ivd::Seeder.seed!
end
config.after(:all) do
# http://renderedtext.com/blog/2012/10/10/cleaning-up-after-before-all-blocks/
DatabaseCleaner.clean_with(:truncation)
end
config.before(:each) do
DatabaseCleaner.strategy = :transaction
end
config.before(:each, js: true) do
# truncation is slower but more reliable
DatabaseCleaner.strategy = :truncation
end
config.before(:each) do
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
end
rails_helper.rb
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../dummy/config/environment.rb', __FILE__)
abort('The Rails environment is running in production mode!') if Rails.env.production?
require 'spec_helper'
require 'rspec/rails'
require 'rails-controller-testing'
# Add additional requires below this line. Rails is not loaded until this point!
require 'devise'
ActiveRecord::Migration.maintain_test_schema!
RSpec.configure do |config|
config.warnings = false
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
config.fixture_path = "#{Ivd::Engine.root}/spec/fixtures"
# above used by fixture_file_upload
# eg in:
# /Users/etewiah/Ed/sites-2016-oct-ivd/ivd/spec/services/ivd/import_properties_spec.rb
config.infer_spec_type_from_file_location!
config.filter_rails_from_backtrace!
[:controller, :view, :request].each do |type|
config.include ::Rails::Controller::Testing::TestProcess, type: type
config.include ::Rails::Controller::Testing::TemplateAssertions, type: type
config.include ::Rails::Controller::Testing::Integration, type: type
end
# https://github.com/plataformatec/devise/wiki/How-To:-Test-controllers-with-Rails-3-and-4-(and-RSpec)
config.include Devise::Test::ControllerHelpers, type: :controller
config.include FeatureHelpers, type: :feature
config.extend ControllerMacros, type: :controller
# https://github.com/plataformatec/devise/wiki/How-To:-Stub-authentication-in-controller-specs
config.include ControllerHelpers, type: :controller
# https://github.com/plataformatec/devise/wiki/How-To:-sign-in-and-out-a-user-in-Request-type-specs-(specs-tagged-with-type:-:request)
config.include RequestSpecHelpers, type: :request
end
I have model User, which has been inherited from ApplicationRecord.
File .rspec contains only:
--color
--require byebug
--require rails_helper
Is your model itself within the module Ivd? i.e.
module Ivd
class User
If so, you want to be using RSpec.describe Ivd::User rather than wrapping the call in the module.
I have a very basic RSpec/Capybara Rails test written down but i keep on getting that expect method is undefined
my spec/features/signin_spec.rb:
require "rails_helper"
RSpec.feature "the signin process", :type => :feature do
before :each do
User.create(:email => "user#example.com", :password => "password")
end
scenario "signs me in" do
visit "/users/sign_in"
within("#new_user") do
fill_in "Email", :with => "user#example.com"
fill_in "Password", :with => "password"
end
click_button "Log in"
expect(page).to have_content "successfully"
end
end
rails_helper:
This file is copied to spec/ when you run 'rails generate rspec:install'
ENV['RAILS_ENV'] ||= 'test'
require 'spec_helper'
require File.expand_path('../../config/environment', __FILE__)
require 'rspec/rails'
ActiveRecord::Migration.maintain_test_schema!
RSpec.configure do |config|
config.include Devise::TestHelpers, type: :controller
config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.use_transactional_fixtures = true
config.infer_spec_type_from_file_location!
end
spec_helper:
require 'capybara/rspec'
RSpec.configure do |config|
config.include Capybara::DSL
config.expect_with(:rspec) { |c| c.syntax = :should }
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
=begin
config.filter_run :focus
config.run_all_when_everything_filtered = true
config.disable_monkey_patching!
if config.files_to_run.one?
config.default_formatter = 'doc'
end
config.profile_examples = 10
config.order = :random
Kernel.srand config.seed
=end
end
Adding :expect to this in spec_helper removed the error
config.expect_with :rspec do |c|
c.syntax = [:should, :expect]
end
https://www.relishapp.com/rspec/rspec-expectations/docs/syntax-configuration#disable-expect-syntax
Thank you for your help #apneadiving and Frederick
Just replace
expectations.syntax = :should
with
expectations.syntax = [:should , :expect]
in your spec_helper.rb
just replace
expectations.syntax = :should
with
expectations.syntax = [:should , :expect]
In your spec_helper.rb
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
I have this route:
post 'create', to: 'applications#create'
this controller:
class ApplicationsController < ApplicationController
def create
end
end
and this test:
require "spec_helper"
describe ApplicationsController do
describe "routing" do
it 'routes to #create' do
post('/applications').should route_to('applications#create')
end
end
end
and this is my spec_helper:
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
ActiveRecord::Migration.maintain_test_schema!
RSpec.configure do |config|
config.expect_with :rspec do |c|
c.syntax = :should
end
config.mock_with :rspec do |c|
c.syntax = :should
end
config.use_transactional_fixtures = true
config.infer_base_class_for_anonymous_controllers = false
config.order = "random"
end
Why when I run
rspec ./spec/routing
I get this error?
Failure/Error: post('/applications').should route_to('applications#create')
NoMethodError:
undefined method `post' for RSpec
I tried changing the test using expect but with no luck. neither with a different class name.
What should I do to test my routes?
UPDATE
If I do this:
it "should return status 200" do
post('/applications'), {}
response.status.should be(200)
end
I get the same error
I am not sure it can help you but I had the same problem when passing to Rspec 3
According to https://relishapp.com/rspec/rspec-rails/docs/directory-structure
we should enable that option to pass automatically metadata.
# spec/rails_helper.rb
RSpec.configure do |config|
config.infer_spec_type_from_file_location!
end
Once this was added my specs passed.
After upgrade my rails app to use rspec 3, the controllers tests broke.
Am I missing something in the rails_helper.rb?
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 { |file| require file }
Dir[Rails.root.join("spec/factories/*.rb")].each { |file| require file }
ActiveRecord::Migration.check_pending! if defined?(ActiveRecord::Migration)
RSpec.configure do |config|
config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.use_transactional_fixtures = true
config.infer_base_class_for_anonymous_controllers = false
config.order = "random"
config.include ApplicationHelper
config.include FactoryGirl::Syntax::Methods
config.include ActionController::TestCase::Behavior
config.include Devise::TestHelpers, type: :controller
config.extend ControllerMacros, type: :controller
config.include(MailerMacros)
config.before(:each) { reset_email }
end
users_controller_spec.eb
require 'rails_helper'
describe UsersController do
describe 'has_user' do
let(:student) { FactoryGirl.create(:student) }
it 'not succeeds password' do
get :has_user, { password: 123 }
expect(response).to have_http_status(:unprocessable_entity)
end
end
end
Failures:
1) UsersController has_user not succeeds password
Failure/Error: get :has_user, { password: 123 }
RuntimeError:
#routes is nil: make sure you set it in your test's setup method.
# ./spec/controllers/users_controller_spec.rb:10:in `block (3 levels) in <top (required)>'
Thanks!
Well, missing this line inside rails_helper.rb as documented here
config.infer_spec_type_from_file_location!