![](/img/trans.png)
[英]Rspec-rails 4 error: ActiveModel::ForbiddenAttributesError
[英]How to Raise Runtime Error in Rspec-Rails
我必須測試出現一些錯誤的代碼,我嘗試了幾種技術但都失敗了。 class的結構定義如下:
架構控制器:
class SchemasController < ApplicationController
def index
@get_schema = Api::AnalyticsQueryBuilderMetadataService::Schema.show
end
end
Api -> AnalyticsQueryBuilderMetadataService -> Schema.rb文件下的顯示方法:
def self.show
params = { 'limit' => 40 }
response = Api::Connection.initiate_request('entities', params)
if response.nil?
Rails.logger.error 'Data not found for ClientId '
raise 'Data not found'
else
get_schema(response)
end
end
我為 schema_spec.rb 編寫的 Rspec 測試:
require 'rails_helper'
require 'spec_helper'
RSpec.describe Api::AnalyticsQueryBuilderMetadataService::Schema do
describe 'GET all schema' do
before do
# allow_any_instance_of(SchemasController).to receive(:connection).and_return({})
#binding.pry
allow(Api::Connection).to receive(:initiate_request).and_return(nil)
end
context 'When no json body is passed' do
it 'Raises NoMethodError' do
# obj = SchemasController.new
result = Api::AnalyticsQueryBuilderMetadataService::Schema.show()
# expect {result}.to raise_error(RuntimeError)
expect{result}.to raise_error
end
end
end
end
但它給出的錯誤是:
Failures:
1) Api::AnalyticsQueryBuilderMetadataService::Schema GET all schema When no json body is passed Raises NoMethodError
Failure/Error: raise 'Data not found'
RuntimeError:
Data not found
# ./app/lib/api/analytics_query_builder_metadata_service/schema.rb:22:in `show'
# ./spec/lib/api/analytics_query_builder_metadata_service/schema_spec.rb:17:in `block (4 levels) in <top (required)>'
Finished in 2.3 seconds (files took 5.63 seconds to load)
44 examples, 1 failure
Failed examples:
rspec ./spec/lib/api/analytics_query_builder_metadata_service/schema_spec.rb:15 # Api::AnalyticsQueryBuilderMetadataService::Schema GET all schema When no json body is passed Raises NoMethodError
幫我解決這個問題。
來自文檔;
使用 raise_error 匹配器指定代碼塊引發錯誤。
這意味着塊中的代碼應該是引發錯誤的代碼,但在您的情況下,當您聲明result
變量時會引發錯誤。
要使其工作,您可以跳過變量聲明並將變量值作為expect
塊傳遞;
expect { Api::AnalyticsQueryBuilderMetadataService::Schema.show }
.to raise_error(StandardError, 'Data not found')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.