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 )
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