Skip to content

Commit 7e29ea1

Browse files
nacchan99rakuda-san-desu
authored andcommitted
test: Newsモデルのバリデーション・スコープのテストを追加
1 parent 4a0616a commit 7e29ea1

File tree

1 file changed

+63
-1
lines changed

1 file changed

+63
-1
lines changed

spec/models/news_spec.rb

Lines changed: 63 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,67 @@
11
require 'rails_helper'
22

33
RSpec.describe News, type: :model do
4-
pending "add some examples to (or delete) #{__FILE__}"
4+
describe 'バリデーション' do
5+
let(:news) { build(:news) }
6+
7+
it '有効なファクトリーを持つ' do
8+
expect(news).to be_valid
9+
end
10+
11+
describe 'title' do
12+
it 'presence: true' do
13+
news.title = nil
14+
expect(news).not_to be_valid
15+
expect(news.errors[:title]).not_to be_empty
16+
end
17+
end
18+
19+
describe 'url' do
20+
it 'presence: true' do
21+
news.url = nil
22+
expect(news).not_to be_valid
23+
expect(news.errors[:url]).not_to be_empty
24+
end
25+
26+
it 'uniqueness: true' do
27+
create(:news, url: 'https://example.com/test')
28+
duplicate_news = build(:news, url: 'https://example.com/test')
29+
expect(duplicate_news).not_to be_valid
30+
expect(duplicate_news.errors[:url]).not_to be_empty
31+
end
32+
33+
it 'URL形式であること' do
34+
news.url = 'invalid-url'
35+
expect(news).not_to be_valid
36+
expect(news.errors[:url]).not_to be_empty
37+
end
38+
39+
it 'HTTPSとHTTPを許可する' do
40+
news.url = 'https://example.com'
41+
expect(news).to be_valid
42+
43+
news.url = 'http://example.com'
44+
expect(news).to be_valid
45+
end
46+
end
47+
48+
describe 'published_at' do
49+
it 'presence: true' do
50+
news.published_at = nil
51+
expect(news).not_to be_valid
52+
expect(news.errors[:published_at]).not_to be_empty
53+
end
54+
end
55+
end
56+
57+
describe 'スコープ' do
58+
describe '.recent' do
59+
it '公開日時の降順で並び替える' do
60+
old_news = create(:news, published_at: 2.days.ago)
61+
new_news = create(:news, published_at: 1.day.ago)
62+
63+
expect(News.recent).to eq([new_news, old_news])
64+
end
65+
end
66+
end
567
end

0 commit comments

Comments
 (0)