Добрый вечер:
Итак, я НОВИНКА в мире тестирования на рельсах. Я следил за этим руководством по API и аутентификации, чтобы попытаться изучить тестирование:
Scotch.io - build-a-restful- json -api-with-rails-5
Теперь это руководство предназначено для Rails 5 (я использую rails 6 - может быть, это как-то связано с проблемой?)
так что происходит, когда я запускаю rails exec rspec
тесты работают нормально, пока Я нажимаю этот блок моего clients_spec.rb
// клиентского контроллера spe c POST-тестов (показано ниже):
describe 'Post /loadze_app/api/v1/clients' do
let(:valid_attributes) { { client_name: 'Mega Client', street_address: '221 some address rd' } }
context 'when the request is valid' do
before { post '/loadze_app/api/v1/clients', params: valid_attributes }
it 'creates a client' do
expect(json['client_name']).to eq('Mega Client')
end
it 'returns status code 201' do
expect(response).to have_http_status(201)
end
end
context 'when the request is invalid' do
before { post '/loadze_app/api/v1/clients', params: { street_address: 'Foobar' } }
it 'returns status code 422' do
expect(response).to have_http_status(422)
end
it 'returns a validation failure message' do
expect(response.body).to match(/Validation failed: Client name can't be blank/)
end
end
end
Когда я удаляю этот блок и снова запускаю тест, все работает как надо. Так что я немного растерялся и изо всех сил пытаюсь найти какие-либо соответствующие исправления на Stack и других ресурсных сайтах.
это ошибка, которую я получаю при запуске rails exec rspec
:
1) Clients API Post /loadze_app/api/v1/clients when the request is valid creates a client
Failure/Error: JSON.parse(response.body)
JSON::ParserError:
784: unexpected token at ''
# ./spec/support/request_spec_helper.rb:3:in `json'
# ./spec/requests/clients_spec.rb:47:in `block (4 levels) in <main>'
# ./spec/rails_helper.rb:42:in `block (3 levels) in <top (required)>'
# ./spec/rails_helper.rb:41:in `block (2 levels) in <top (required)>'
Вот все файлы, на которые ссылается ошибка: я обозначил строку с помощью ** Line # **
/ spec / support / request_spec_helper.rb: 3
module RequestSpecHelper
def json
JSON.parse(response.body) ** Line 3
end
end
/ spec / requests / clients_spe c .rb: 47
describe 'Post /loadze_app/api/v1/clients' do
let(:valid_attributes) { { client_name: 'Mega Client', street_address: '421 Rundleson Pl N.E' } }
context 'when the request is valid' do
before { post '/loadze_app/api/v1/clients', params: valid_attributes }
it 'creates a client' do
expect(json['client_name']).to eq('Mega Client') **Line 47**
end
it 'returns status code 201' do
expect(response).to have_http_status(201)
end
end
context 'when the request is invalid' do
before { post '/loadze_app/api/v1/clients', params: { street_address: 'Foobar' } }
it 'returns status code 422' do
expect(response).to have_http_status(422)
end
it 'returns a validation failure message' do
expect(response.body).to match(/Validation failed: Client name can't be blank/)
end
end
end
/ spec / rails_helper.rb: 41/42
require 'database_cleaner'
require 'spec_helper'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../config/environment', __dir__)
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'rspec/rails'
# Add additional requires below this line
begin
ActiveRecord::Migration.maintain_test_schema!
rescue ActiveRecord::PendingMigrationError => e
puts e.to_s.strip
exit 1
end
Shoulda::Matchers.configure do |config|
config.integrate do |with|
with.test_framework :rspec
with.library :rails
end
end
Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
RSpec.configure do |config|
config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.use_transactional_fixtures = true
config.infer_spec_type_from_file_location!
config.filter_rails_from_backtrace!
config.include FactoryBot::Syntax::Methods
config.include RequestSpecHelper, type: :request
config.before(:suite) do
DatabaseCleaner.clean_with(:truncation)
DatabaseCleaner.strategy = :transaction
end
config.around(:each) do |example|
DatabaseCleaner.cleaning do **Line 41**
example.run ** Line 42**
end
end
end
Любая помощь в решении этой проблемы была бы БОЛЬШОЙ признательна! Пожалуйста, дайте мне знать, если потребуется дополнительная информация! Заранее спасибо!