Skip to content

Commit ed60e2e

Browse files
committed
🔌 /news.json API エンドポイントを追加
- NewsController に JSON レスポンス機能を実装 - respond_to で HTML と JSON の両形式に対応 - RSpec でテストケースを追加して動作を保証
1 parent 4afae7b commit ed60e2e

File tree

2 files changed

+60
-2
lines changed

2 files changed

+60
-2
lines changed

app/controllers/news_controller.rb

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,5 +6,10 @@ def index
66

77
# データベースからニュースデータを取得(最新順)
88
@news_items = News.recent
9+
10+
respond_to do |format|
11+
format.html # デフォルトのHTMLビュー
12+
format.json { render json: @news_items }
13+
end
914
end
1015
end

spec/requests/news_spec.rb

Lines changed: 55 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
published_at: 2.days.ago
1111
)
1212
@news2 = News.create!(
13-
title: "テストニュース2",
13+
title: "テストニュース2",
1414
url: "https://example.com/news2",
1515
published_at: 1.day.ago
1616
)
@@ -63,4 +63,57 @@
6363
expect(response.body).to include("現在、ニュース記事はありません")
6464
end
6565
end
66-
end
66+
67+
describe "GET /news.json" do
68+
before do
69+
# テスト用のニュースデータを作成
70+
@news1 = News.create!(
71+
title: "テストニュース1",
72+
url: "https://example.com/news1",
73+
published_at: 2.days.ago
74+
)
75+
@news2 = News.create!(
76+
title: "テストニュース2",
77+
url: "https://coderdojo.jp/podcasts/2",
78+
published_at: 1.day.ago
79+
)
80+
end
81+
82+
it "JSON形式でレスポンスを返す" do
83+
get news_index_path(format: :json)
84+
expect(response).to have_http_status(:success)
85+
expect(response.content_type).to match(/application\/json/)
86+
end
87+
88+
it "ニュースデータをJSON形式で返す" do
89+
get news_index_path(format: :json)
90+
json = JSON.parse(response.body)
91+
92+
expect(json).to be_an(Array)
93+
expect(json.length).to eq(2)
94+
95+
# 新しい順に返されることを確認
96+
expect(json[0]["title"]).to eq("テストニュース2")
97+
expect(json[1]["title"]).to eq("テストニュース1")
98+
end
99+
100+
it "各ニュースアイテムに必要な属性が含まれる" do
101+
get news_index_path(format: :json)
102+
json = JSON.parse(response.body)
103+
104+
first_news = json[0]
105+
expect(first_news).to have_key("id")
106+
expect(first_news).to have_key("title")
107+
expect(first_news).to have_key("url")
108+
expect(first_news).to have_key("published_at")
109+
end
110+
111+
it "ニュースがない場合は空の配列を返す" do
112+
News.destroy_all
113+
get news_index_path(format: :json)
114+
115+
json = JSON.parse(response.body)
116+
expect(json).to eq([])
117+
end
118+
end
119+
end

0 commit comments

Comments
 (0)