Relationship validations
再繼續之前,我們要先增加一些 Relationship model 的驗證機制。
下面的 test 和應用程式碼非常直觀。就像之前產生的 user fixture(Section 6.2.5),relationship fixture 也違反了遷移的唯一約束性。這個問題的解決方法也和之前一樣,刪除自動產生的 fixture。
Listing 12.4: 測試 Relationship model 的驗證機制
test/models/relationship_test.rb
require 'test_helper'
class RelationshipTest < ActiveSupport::TestCase
def setup
@relationship = Relationship.new(follower_id: 1, followed_id: 2)
end
test "should be valid" do
assert @relationship.valid?
end
test "should require a follower_id" do
@relationship.follower_id = nil
assert_not @relationship.valid?
end
test "should require a followed_id" do
@relationship.followed_id = nil
assert_not @relationship.valid?
end
end
Listing 12.5: 增加 Relationship model 驗證機制
app/models/relationship.rb
class Relationship < ActiveRecord::Base
belongs_to :follower, class_name: "User"
belongs_to :followed, class_name: "User"
validates :follower_id, presence: true
validates :followed_id, presence: true
end
Listing 12.6: 移除 relationship fixture 內容
test/fixtures/relationships.yml
# empty
現在執行測試應該會通過:
Listing 12.7: Green
$ bundle exec rake test