Skip to content

Instantly share code, notes, and snippets.

@IFilonov
Last active April 11, 2023 12:51
Show Gist options
  • Select an option

  • Save IFilonov/4590d07e33fc2984c8cb92e9167590b8 to your computer and use it in GitHub Desktop.

Select an option

Save IFilonov/4590d07e33fc2984c8cb92e9167590b8 to your computer and use it in GitHub Desktop.
Rspec example:
describe Class, type: :service do
let(a) { build(:a) }
let!(b) { build_stubbed(:b) }
let!(c) { create(:c) }
before do
VCR.turn_off!
WebMock.enable!
WebMock.allow_net_connect! --разрешить реальные запросы
resource_iaas = double('resource_iaas')
expect(Orchestrator::Resources::Iaas).to receive(:new).and_return(resource_iaas)
stub_const('Constants::ZONE', 'TEST')
stub_const('ENV', 'USER' => 'ADMIN')
stub_const('ENV', ENV.to_h.merge('SKIP_CAS' => 'false'))
stub_request(:get, url).with(query: query).to_return(status: 200, body: body.to_json) --WebMock stub
stub_request(:post, url).with(body: "abc", headers: { 'Content-Length' => 3 })
allow(Rails.logger).to receive(:info)
allow_any_instance_of(OrchestratorAdapter).to receive(:find_orders).and_return('data' => [orch_data])
allow_any_instance_of(CloudStorageOrder).to receive(:delete_namespace).and_raise(StandardError, 'namespace is not empty')
allow_any_instance_of(XvdcOrder).to receive_message_chain(:resource_iaas, :rpc_call).and_return({ user: 1 })
allow(Redis).to receive(:new).and_return(MockRedis.new) --MockRedis stub
end
context 'context description', :focus do
before do
expect_any_instance_of(BaasNetBackupWithPlanOrder).to receive(:cidrs_for_nat).and_return('data' => [123])
end
it 'example description', :aggregate_failures do
expect(Notifications).to receive_message_chain(:with, :alarm, :deliver_later)
expect { described_class.method }.to_not raise_error
expect { order_resources }.to raise_error(OrchestratorAdapter::ServerError, 'Internal Server Error')
expect(described_class.method).to eq(0)
expect(WebMock).to have_requested(:get, url).once
expect(described_class.new(params)).to match(/success/)
expect(File).to exist(File.join('/tmp',"network_report_#{Time.now.strftime('%Y%m%d_%H%M')}.csv"))
--Пишем VCR кассету:
VCR.use_cassette('cassetes') do
expect(IaasController.new.connect_baas_network(params)).to eq(["connect_to_baas_network_complete", {}])
end
-- Испольузем кассету
it 'successful connected', vcr: { cassette_name: 'folder/connect_network' } do
expect(IaasController.new.connect_network(params)).to eq('network_connected')
end
end
expect { described_class.new.update_statistic }
.to change { Orchestrator::Models::IpUsageStatistic.count }
.from(1).to(2)
it 'correct logger messages' do
expect(Rails.logger).to receive(:info).with("--- ERRORS ---").ordered.and_call_original
expect(Rails.logger).to receive(:info).at_least(:once).with("ERROR: #{error_id}")
end
it 'pending, not emplementing yet'
end
after do
puts 'after do'
end
end
------------------------
rspec --init # create config files and folders in project
rspec -e 'invalid' # run tests where 'invalid' word in it/context example exist
rspec -e 'invalid' -f d # previous command in extended documentation format
rspec -e 'invalid' -f d --dry-run # previous command but without running test, only text output
rspec --fail-fast # stop after first crashed test
config.filter_run_when_matching :focus -> spec_helper.rb
rspec --tag focus # run it/context/describe specs which has :focus tag or fit/fcontext/fdescibe
rspec --tag type:model # run only model specs
rspec --tag ~type:model # run all specs except model specs
config.example_status_persistence_file_path = "tmp/rspec_log.txt" -> spec_helper.rb # log test specs
rspec # generate tmp/rspec_log.txt after config editing
rspec --only-failures # run only failed test based on tmp/rspec_log.txt
rspec --next-failure # run first failed test based on tmp/rspec_log.txt
rspec --bisect # generate commands to run only failed specs separately
*** change format log *****************
gem 'fuubar' -> gemfile (in test group)
--format Fuubar -> .rspec
*** delete warning logs ***************
gem 'warning' -> gemfile (in test group)
into rspec_helper.rb:
require 'warning'
Warning.ignore(/Active Record does not support composite primary key/)
*** GEMS ******************************
gem 'json_spec'
expect(response.body).to be_json_eq('test value').at_path('data/0/json_key')
gem 'email_spec'
config.include EmailSpec::Helpers -> rails_helper.rb
mailbox_for(email).size
************ VCR config *****************
VCR.configure do |config|
config.cassette_library_dir = "fixtures/vcr"
config.hook_into :webmock
config.debug_logger = $stderr
config.configure_rspec_metadata!
config.default_cassette_options = { record: :once }
config.before_record do |record|
record.response.body.force_encoding('UTF-8')
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment