C83 / THP_2.0

0 stars 0 forks source link

Create Lesson model #6

Closed C83 closed 6 years ago

C83 commented 6 years ago

Why ?

We will create our first model and learn how to test it, validate it (at the model level) and constrain it at the DB level.

A lesson will be a container for each thing we want to teach.

Must have

Migration

Model

Test it

Reading list

C83 commented 6 years ago

Migration :

Command : rails generate model lesson title:string{50} description:text{300} We can't define a parameter "can't be empty" with command line. Then in migrate file :

t.string :title, limit: 50, null:false
t.text :description, limit: 300 

Validation

In lesson model file :

validates :title, presence: true, length: { maximum: 50 }
validates :description, length: { maximum: 300 }
C83 commented 6 years ago

Test

Factory :

require 'faker'

FactoryBot.define do
  factory :lesson do
    title Faker::Hacker.noun
    description Faker::ChuckNorris.fact
  end
end

Creation and validation :

Creation and save test with expect and factory_bot. With factory_bot, build builds an instance of object. create saves and persists it.

it "is valid with valid attributes" do
    expect(build(:lesson)).to be_valid
  end

Some tests are rewritten with should gem :

it { should validate_presence_of(:title) }