Skip to content

Commit 17b574b

Browse files
committed
🐛 rack-user_agent の variant が JSON レスポンスに影響しないように修正
問題: - rack-user_agent gem が設定する request.variant (pc, smartphone等) により JSON形式のレスポンス時にテンプレート探索エラーが発生 - ActionController::UnknownFormat エラーで /news.json が500エラーになっていた 解決: - NewsController で JSON レスポンス時は request.variant = nil を設定 - device variant の影響を受けずに正しく JSON を返すように修正 TDD実践: - まずvariant設定時のテストを追加(RED) - その後修正を適用してテスト成功を確認(GREEN)
1 parent 8b21922 commit 17b574b

File tree

2 files changed

+41
-1
lines changed

2 files changed

+41
-1
lines changed

app/controllers/news_controller.rb

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,12 @@ def index
99

1010
respond_to do |format|
1111
format.html # デフォルトのHTMLビュー
12-
format.json { render json: @news_items }
12+
format.json {
13+
# JSON レスポンス時は variant を無視する
14+
# rack-user_agent gem による variant 設定が JSON レスポンスに影響しないようにする
15+
request.variant = nil
16+
render json: @news_items
17+
}
1318
end
1419
end
1520
end

spec/requests/news_spec.rb

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,41 @@
7979
)
8080
end
8181

82+
context "variant が設定されている場合" do
83+
it "variant :pc が設定されていても JSON 形式でレスポンスを返す" do
84+
# rack-user_agent gem が PC からのアクセスで variant :pc を設定する状況を再現
85+
# set_request_variant をオーバーライドして variant を強制的に設定
86+
allow_any_instance_of(NewsController).to receive(:set_request_variant) do |controller|
87+
controller.request.variant = :pc
88+
end
89+
90+
get news_index_path(format: :json)
91+
92+
expect(response).to have_http_status(:success)
93+
expect(response.content_type).to match(/application\/json/)
94+
95+
json = JSON.parse(response.body)
96+
expect(json).to be_an(Array)
97+
expect(json.length).to eq(2)
98+
end
99+
100+
it "variant :smartphone が設定されていても JSON 形式でレスポンスを返す" do
101+
# rack-user_agent gem がモバイルからのアクセスで variant :smartphone を設定する状況を再現
102+
allow_any_instance_of(NewsController).to receive(:set_request_variant) do |controller|
103+
controller.request.variant = :smartphone
104+
end
105+
106+
get news_index_path(format: :json)
107+
108+
expect(response).to have_http_status(:success)
109+
expect(response.content_type).to match(/application\/json/)
110+
111+
json = JSON.parse(response.body)
112+
expect(json).to be_an(Array)
113+
expect(json.length).to eq(2)
114+
end
115+
end
116+
82117
it "JSON形式でレスポンスを返す" do
83118
get news_index_path(format: :json)
84119
expect(response).to have_http_status(:success)

0 commit comments

Comments
 (0)