1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Rails: アクションによってバリデーションを切り替えた時の、モデルのテスト方法

Last updated at Posted at 2015-09-17

「[状況によってsave時に実行するバリデーションを切り替える] (http://qiita.com/kadoppe/items/061d137e6022fa099872)」という記事が役立った。

ではテストではどうすれば良いのか?
.on(:action_name) を使おう。

app/models/user.rb
class User
  validates :name, presence: true, on: :index
  validates_length_of :introduction, maximum: 10000. on: :create
end
spec/models/user_spec.rb
require 'spec_helper'

describe User, type: :model do
  it { should validate_presence_of(:name).on(:index) }
  it { should validate_length_of(:introduction).is_at_most(10000).on(:create) }
end

書き方は Rspec でも Test::Unit でも同じ感じ。

ただし、 validate_numericality_of.on(:index) は出来なかった。
( GitHubの説明通りに書いてもなぜか NoMethodError )

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

メンター受付

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?