0

ユーザーモデルに属するチュートリアルモデルがあります。チュートリアルのタイトルは、ユーザー レベルごとに固有のものにしたいと考えています。したがって、2 人のユーザーが同じタイトルのチュートリアルを持つことはできますが、1 人のユーザーが同じタイトルの 2 つのチュートリアルを持つことはできません。私のテストは失敗していますが、繰り返されるタイトルを除外することを修正していることはわかっています。テストの何が問題になっていますか?

# model - tutorial.rb
class Tutorial < ActiveRecord::Base
  attr_accessible :title
  belongs_to :user

  validates :user_id, presence: true
  validates :title, presence: true, length: { maximum: 140 }, uniqueness: { :scope => :user_id }
end

# spec for model
require 'spec_helper'
describe Tutorial do
  let(:user) { FactoryGirl.create(:user) }
  before do
    @tutorial = FactoryGirl.create(:tutorial, user: user)
  end

  subject { @tutorial }

  describe "when a title is repeated" do
    before do
      tutorial_with_same_title = @tutorial.dup
      tutorial_with_same_title.save
    end
    it { should_not be_valid }
  end
end

# rspec output
Failures:
  1) Tutorial when a title is repeated 
     Failure/Error: it { should_not be_valid }
       expected valid? to return false, got true
     # ./spec/models/tutorial_spec.rb:50:in `block (3 levels) in <top (required)>'
4

1 に答える 1

1

テストの問題は次の行です。

it { should_not be_valid }

valid?この仕様は、テストの対象をチェックし@tutorialます。これは有効です。

推奨されるリファクタリング:

describe Tutorial do
  let(:user) { FactoryGirl.create(:user) }
  before do
    @tutorial = FactoryGirl.create(:tutorial, user: user)
  end

  subject { @tutorial }

  describe "when a title is repeated" do
    subject { @tutorial.dup }
    it { should_not be_valid }
  end
end
于 2013-01-19T00:10:35.027 に答える