との見解を打つません: - render_views
含む - JSON::ParserError: A JSON text must at least contain two octets!
RSpecのテストでは、Railsのコントローラ内のindexアクションと応答をテストするためにはRSpecを使用しているとき、私はこのエラーを取得していますrender_view
最も一般的な修正プログラムが動作していないとnil
は渡されていません。このテストではビューがヒットしていません。コントローラーのインデックスアクションにrender json: {test: 'hello world'}, status: 200 and return
を挿入し、ビュー内で(index.json.jbuilder
)、get :index
の後に応答ボディがあることがわかります。テストの期待値をexpect(response).to render_template '[]'
に変更した場合、応答本体にある空の配列を見ることができます。 render_viewsが失敗し、なぜそれを再び働かせるのですか?ここで
はindex_spec.rbです:ここでは
require 'rails_helper'
RSpec.describe ThingsController, type: :controller do
render_views
let(:json_response) { JSON.parse(response.body) }
let(:status) { response.status }
let(:user) { create(:user_with_associations) }
subject{ ThingsController }
describe "GET #index" do
context "(success cases)" do
before(:each) do
expect_any_instance_of(subject).to receive(:set_user_by_token).and_return(user)
end
context "and when there are no things" do
before(:each) do
get :index
end
it "returns a 200 status" do
expect(status).to eq 200
end
it "returns a top level key of data with an empty array" do
expect(json_response["data"]).to eq []
end
end
end
end
はrails_helper.rbです:
ENV["RAILS_ENV"] ||= 'test'
require_relative 'spec_helper'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
ActiveRecord::Migration.maintain_test_schema!
RSpec.configure do |config|
config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.use_transactional_fixtures = true
config.before(:suite) do
DatabaseCleaner.strategy = :transaction
DatabaseCleaner.clean_with(:truncation)
end
config.before(:each) do
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
config.infer_spec_type_from_file_location!
end
そしてここでは、ここではspec_helper.rb
ENV["RAILS_ENV"] ||= 'test'
require 'factory_girl_rails'
require 'faker'
include ActionDispatch::TestProcess
RSpec.configure do |config|
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
config.include FactoryGirl::Syntax::Methods
config.before do
FactoryGirl.factories.clear
FactoryGirl.find_definitions
end
end
そして、コントローラのですテスト中の動作things_controller.rb:
class ThingsController < ApplicationController
before_action :authenticate_user!, only: [ :index ]
before_action -> {check_last_updated("Thing")}, only: [ :index ]
def index
@things = @current_user.things.in_last_three_months.approved_and_unapproved.order(start_time: :asc)
end
end
Railsの4.2.0 ルビー2.1.2 RSpecの3.5.4
これは、ここで私の最初の質問ですので、含まれるべき他の情報がある場合は私に知らせてください。