36. $vi /spec/models/contact_spec.rb
require 'spec_helper'
describe Contact do
it "全てのデータが有効な状態であること"
it "名前がなければ無効な状態であること"
it "メールがなければ無効な状態であること"
it "重複したメールアドレスなら無効な状態であること"
end
まず、期待する動作をアウトライン的に
書き出してみる。
51. require 'spec_helper'
describe Contact do
it "名前がなければ無効な状態であること" do
contact = Contact.new(
name: nil
)
expect(contact).to have(1).errors_on(:name)
end
it "メールがなければ無効な状態であること" do
contact = Contact.new(
email: nil
)
expect(contact).to have(1).errors_on(:email)
end
end
nameのデータを空にして
エラーがでるかテスト
60. require 'spec_helper'
describe Contact do
it "名前付きメールアドレスを返すこと" do
contact = Contact.new(
name: 'zaru',
email: 'zaru@example.com'
)
expect(contact.nameAddr).to
eq 'zaru<zaru@example.com>'
end
end
nameAddrを実行して、かえってくる文字列を比較する
62. beforeフックで、まとめる
require 'spec_helper'
describe Contact do
before :each do
@contact = Contact.new(
name: 'zaru',
email: 'zaru@example.com'
)
end
end
Contactオブジェクトをインスタンス変数に格納
beforeは、describe中の各テストの前に実行される
68. it "全てのデータが有効な状態であること" do
contact = Contact.new(
name: 'zaru',
email: 'zaru@example.com'
)
expect(contact).to be_valid
end
it "全てのデータが有効な状態であること" do
expect(FactoryGirl.build(:contact)).to be_valid
end
こうなる
FactoryGirl.buildで、Contact.newと同様のことができる。
FactoryGirl.createで、Contact.createと同じ。
71. $vi /spec/spec_helper.rb
RSpec.configure do |config|
config.include FactoryGirl::Syntax::Methods
end
it "全てのデータが有効な状態であること" do
expect(build(:contact)).to be_valid
end
FactoryGirl省略できる