Tuesday, 18 July 2023

Create test case, step by step

 1. Add in the Gemfile file:

group :development, :test do

  # Call 'byebug' anywhere in the code to stop execution and get a debugger console

  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]

  gem 'rspec-rails', '5.1.2'

  gem 'rspec-sonarqube-formatter', '1.5.0'

  gem 'database_cleaner-active_record'

  gem 'simplecov', '0.17'

  gem 'simplecov-json', :require => false

  gem 'simplecov-rcov'

  gem 'factory_bot_rails'

  gem 'shoulda-matchers'

  gem 'shoulda-callback-matchers'

  gem "letter_opener"

end

group :development do

  gem 'dotenv-rails' #this gem use only for .env file

end


-----------------------------------------------------------


2. in /spec/rails_helper.rb

# require 'simplecov'


# SimpleCov.start('rails')

require 'spec_helper'

ENV['RAILS_ENV'] ||= 'test'

require_relative '../config/environment'

# require File.expand_path('../config/environment', _dir_)

abort("The Rails environment is running in production mode!") if Rails.env.production?

require 'rspec/rails'

# require 'database_cleaner'

# Dotenv.load('.env.test')

Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}

begin

  ActiveRecord::Migration.maintain_test_schema!

rescue ActiveRecord::PendingMigrationError => e

  puts e.to_s.strip

  exit 1

end

RSpec.configure do |config|

  config.use_transactional_fixtures = false

  config.include FactoryBot::Syntax::Methods

  config.infer_spec_type_from_file_location!

  config.filter_rails_from_backtrace!

  

  config.include Devise::TestHelpers, type: :controller

  # arbitrary gems may also be filtered via:

  # config.filter_gems_from_backtrace("gem name")

  config.include(Shoulda::Callback::Matchers::ActiveModel)

  # config.before(:suite) do

  #   DatabaseCleaner.clean_with(:truncation)

  # end

  # config.before(:each) do

  #   DatabaseCleaner.strategy = :transaction

  # end

  # config.before(:each, :js => true) do

  #   DatabaseCleaner.strategy = :truncation

  # end

  # config.before(:each) do

  #   DatabaseCleaner.start

  # end

  # config.after(:each) do

  #   DatabaseCleaner.clean

  # end

  # config.before(:all) do

  #   DatabaseCleaner.start

  # end

  # config.after(:all) do

  #   DatabaseCleaner.clean

  # end

  Shoulda::Matchers.configure do |config|

    config.integrate do |with|

      with.test_framework :rspec

      with.library :rails

    end

  end

 RSpec.configure do |config|

    config.include(Shoulda::Callback::Matchers::ActiveModel)

  end

end


------------------------------------------------------------


3. In /spec/spec_helper.rb

3.1. For server:


require 'simplecov'

require 'simplecov-json'


SimpleCov.formatter = SimpleCov::Formatter::JSONFormatter

SimpleCov.start('rails') do

  add_group "Models", "app / models"

  add_group "Controllers", "app/controllers"

  add_group "Multiple Files", ["app/models", "app/controllers"]

  add_group "bx_blocks", %r{ bx_block.*}

  add_filter %r{vendor/ruby/ruby/2.*}

end


# This file was generated by the `rails generate rspec:install` command. Conventionally, all

# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.

# The generated `.rspec` file contains `--require spec_helper` which will cause

# this file to always be loaded, without a need to explicitly require it in any

# files.

#

# Given that it is always loaded, you are encouraged to keep this file as

# light-weight as possible. Requiring heavyweight dependencies from this file

# will add to the boot time of your test suite on EVERY test run, even for an

# individual file that may not need all of that loaded. Instead, consider making

# a separate helper file that requires the additional dependencies and performs

# the additional setup, and require it from the spec files that actually need

# it.

#

# See https://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration

RSpec.configure do |config|

  # rspec-expectations config goes here. You can use an alternate

  # assertion/expectation library such as wrong or the stdlib/minitest

  # assertions if you prefer.

  config.expect_with :rspec do |expectations|

    # This option will default to `true` in RSpec 4. It makes the `description`

    # and `failure_message` of custom matchers include text for helper methods

    # defined using `chain`, e.g.:

    #     be_bigger_than(2).and_smaller_than(4).description

    #     # => "be bigger than 2 and smaller than 4"

    # ...rather than:

    #     # => "be bigger than 2"

    expectations.include_chain_clauses_in_custom_matcher_descriptions = true

  end


  # rspec-mocks config goes here. You can use an alternate test double

  # library (such as bogus or mocha) by changing the `mock_with` option here.

  config.mock_with :rspec do |mocks|

    # Prevents you from mocking or stubbing a method that does not exist on

    # a real object. This is generally recommended, and will default to

    # `true` in RSpec 4.

    mocks.verify_partial_doubles = true

  end


  # This option will default to `:apply_to_host_groups` in RSpec 4 (and will

  # have no way to turn it off -- the option exists only for backwards

  # compatibility in RSpec 3). It causes shared context metadata to be

  # inherited by the metadata hash of host groups and examples, rather than

  # triggering implicit auto-inclusion in groups with matching metadata.

  config.shared_context_metadata_behavior = :apply_to_host_groups


# The settings below are suggested to provide a good initial experience

# with RSpec, but feel free to customize to your heart's content.

=begin

  # This allows you to limit a spec run to individual examples or groups

  # you care about by tagging them with `:focus` metadata. When nothing

  # is tagged with `:focus`, all examples get run. RSpec also provides

  # aliases for `it`, `describe`, and `context` that include `:focus`

  # metadata: `fit`, `fdescribe` and `fcontext`, respectively.

  config.filter_run_when_matching :focus


  # Allows RSpec to persist some state between runs in order to support

  # the `--only-failures` and `--next-failure` CLI options. We recommend

  # you configure your source control system to ignore this file.

  config.example_status_persistence_file_path = "spec/examples.txt"


  # Limits the available syntax to the non-monkey patched syntax that is

  # recommended. For more details, see:

  # https://relishapp.com/rspec/rspec-core/docs/configuration/zero-monkey-patching-mode

  config.disable_monkey_patching!


  # Many RSpec users commonly either run the entire suite or an individual

  # file, and it's useful to allow more verbose output when running an

  # individual spec file.

  if config.files_to_run.one?

    # Use the documentation formatter for detailed output,

    # unless a formatter has already been configured

    # (e.g. via a command-line flag).

    config.default_formatter = "doc"

  end


  # Print the 10 slowest examples and example groups at the

  # end of the spec run, to help surface which specs are running

  # particularly slow.

  config.profile_examples = 10


  # Run specs in random order to surface order dependencies. If you find an

  # order dependency and want to debug it, you can fix the order by providing

  # the seed, which is printed after each run.

  #     --seed 1234

  config.order = :random


  # Seed global randomization in this process using the `--seed` CLI option.

  # Setting this allows you to use `--seed` to deterministically reproduce

  # test failures related to randomization by passing the same `--seed` value

  # as the one that triggered the failure.

  Kernel.srand config.seed

=end

end


3.2 For local


require 'simplecov'

RSpec.configure do |config|

  config.expect_with :rspec do |expectations|

    

    expectations.include_chain_clauses_in_custom_matcher_descriptions = true

  end

  SimpleCov.start 'rails'

  config.mock_with :rspec do |mocks|

   

    mocks.verify_partial_doubles = true

  end


  config.shared_context_metadata_behavior = :apply_to_host_groups


=begin

  config.filter_run_when_matching :focus


  config.example_status_persistence_file_path = "spec/examples.txt"


  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

--------------------------------------------------------------

4. In /spec/factories/account.rb


FactoryBot.define do

  factory :account, :class => AccountBlock::Account do

    email  { Faker::Internet.unique.free_email }

    first_name { Faker::Name.name }

    last_name { Faker::Name.name }

    password {"qweQwe123" }

    full_phone_number {"91#{Faker::Base.numerify('99########')}"}

    activated {"true"}

    twitter_url { "https://twitter.com"}

    linkedin_url { "https://linkedin.com"}

    facebook_url { "https://facebook.com"}

    code { Faker::Alphanumeric.alpha(number: 15) }

  end

end




----------------------------------------------------------------------------

5. Write test case:
5.1 For Active admin : Create admin folder in spac: 

/spec/admin/categories_spec.rb

require 'rails_helper'
require 'spec_helper'
include Warden::Test::Helpers

RSpec.describe Admin::CategoriesController, type: :controller do  render_views

  before(:each) do
    # @category = FactoryBot.create(:category)
    
    @admin = AdminUser.find_or_create_by(email: 'admin1@example.com')
    @admin.password = 'password'
    @admin.save
    sign_in @admin
  end

  it 'get all categories' do
    get :index
    expect(response).to have_http_status :ok
    expect(response).to be_successful
    expect(response.body).to include('category')
  end
  private
  def category
        #some code here
  end
end
-----------------------
5.2 For controller in 

/spec/controllers/account_block/accounts_controller_spec.rb

require 'rails_helper'
RSpec.describe AccountBlock::AccountsController, type: :controller do
  before(:each) do
    @account = FactoryBot.build(:account)
    @account.save(validate: false)
    @token = BuilderJsonWebToken::JsonWebToken.encode(@account.id)
    @account_pass = "Test@123"
    @account_valid_pass = "Test123"
    @account2 = FactoryBot.build(:account, user_role: 'Speaker')
    @account2.save(validate: false)
  end


  describe 'POST account_block/accounts' do
    it 'Invalid email' do
      post :create, params: invalid_email_params
      expect(response.status).to eq 422
      expect(JSON.parse(response.body)['errors']['account'].join('')).to eq "Invalid email."
    end

    it 'Valid password' do
      post :create, params: valid_password_params
      expect(response.status).to eq 422
      expect(JSON.parse(response.body)['errors']['password'].join('')).to eq "Password should contain minimum 8 characters, 1 uppercase, 1 number, 1 special character."
    end
  end
end

---------------------------

5.3 For model in 

/spec/models/account_block/account_spec.rb

# frozen_string_literal: true

require 'rails_helper'

RSpec.describe User, type: :model do


before(:each) do

    @account = FactoryBot.build(:account)

    @account.save(:validate => false)

    

    

    @account.create_new_cvent_auth_for_gerenrate_token_speaker_delete

    @account.cvent_auth_token_for_delete

    @account.create_new_cvent_auth_for_gerenrate_token

  end


  describe "check_validation_screen1_for_product_type" do

    let(:account) { AccountBlock::Account.new(first_name: "testing", last_name: "testins") }

  end


  describe "Enum" do

    it { should define_enum_for(:user_role).with_values({ 'Speaker' => 0}) }

  end


end