|
1 | 1 | require 'rails_helper'
|
2 | 2 |
|
3 | 3 | 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 | + describe 'title' do |
| 8 | + it 'タイトルが空の場合は無効になる' do |
| 9 | + news.title = nil |
| 10 | + expect(news).not_to be_valid |
| 11 | + expect(news.errors[:title]).not_to be_empty |
| 12 | + end |
| 13 | + |
| 14 | + it 'タイトルが正しく設定されている場合は有効になる' do |
| 15 | + news.title = '有効なタイトル' |
| 16 | + expect(news).to be_valid |
| 17 | + end |
| 18 | + end |
| 19 | + |
| 20 | + describe 'url' do |
| 21 | + context '無効な場合' do |
| 22 | + it 'URL が空の場合は無効になる' do |
| 23 | + news.url = nil |
| 24 | + expect(news).not_to be_valid |
| 25 | + expect(news.errors[:url]).not_to be_empty |
| 26 | + end |
| 27 | + |
| 28 | + it 'URL が重複している場合は無効になる' do |
| 29 | + create(:news, url: 'https://example.com/test') |
| 30 | + duplicate_news = build(:news, url: 'https://example.com/test') |
| 31 | + expect(duplicate_news).not_to be_valid |
| 32 | + expect(duplicate_news.errors[:url]).not_to be_empty |
| 33 | + end |
| 34 | + |
| 35 | + it 'URL形式でない場合は無効になる' do |
| 36 | + news.url = 'invalid-url' |
| 37 | + expect(news).not_to be_valid |
| 38 | + expect(news.errors[:url]).not_to be_empty |
| 39 | + end |
| 40 | + end |
| 41 | + |
| 42 | + context '有効な場合' do |
| 43 | + it 'HTTPSを許可する' do |
| 44 | + news.url = 'https://example.com' |
| 45 | + expect(news).to be_valid |
| 46 | + end |
| 47 | + |
| 48 | + it 'HTTPを許可する' do |
| 49 | + news.url = 'http://example.com' |
| 50 | + expect(news).to be_valid |
| 51 | + end |
| 52 | + end |
| 53 | + end |
| 54 | + |
| 55 | + describe 'published_at' do |
| 56 | + it '公開日時が空の場合は無効になる' do |
| 57 | + news.published_at = nil |
| 58 | + expect(news).not_to be_valid |
| 59 | + expect(news.errors[:published_at]).not_to be_empty |
| 60 | + end |
| 61 | + |
| 62 | + it '公開日時が正しく設定されている場合は有効になる' do |
| 63 | + news.published_at = Time.current |
| 64 | + expect(news).to be_valid |
| 65 | + end |
| 66 | + end |
| 67 | + end |
| 68 | + |
| 69 | + describe 'スコープ' do |
| 70 | + describe '.recent' do |
| 71 | + it '公開日時の降順で並び替える' do |
| 72 | + old_news = create(:news, published_at: 2.days.ago) |
| 73 | + new_news = create(:news, published_at: 1.day.ago) |
| 74 | + |
| 75 | + expect(News.recent).to eq([new_news, old_news]) |
| 76 | + end |
| 77 | + end |
| 78 | + end |
5 | 79 | end
|
0 commit comments