banco de dados de uma maneira estruturada e organizada ActiveRecord armazena quais migrations foram executadas utilizando timestamps Tudo o que precisamos fazer é atualizar o código e executar $ rake db:migrate Vamos analizar a anatomia de uma migration @jlucasps
change add_column :products, :size, :integer, :null => :false end end Rails consegue identificar rollback a partir da release, bem como release a partir do rollback release <-> rollback
e manipulação de dado. Realizam esta tarefa de forma independente de um banco de dados específico @jlucasps Data Definition Language (DDL) CREATE ALTER DROP Data Manipulation Language (DML) SELECT UPDATE DELETE
$ bundle install Criar o arquivo /spec/models/user_spec.rb @jlucasps # -*- coding: utf-8 -*- require 'spec_helper' describe User do it { should allow_mass_assignment_of :name } it { should allow_mass_assignment_of :email } it "creates an user" do user = User.new(:name => "João Lucas", :email => "[email protected]", :age => 24) user.save.should be_true end end
....FFF Failures: 1) User 2) User 3) User creates an user Finished in 0.35138 seconds 7 examples, 3 failures Failed examples: rspec ./spec/models/user_spec.rb:7 # User rspec ./spec/models/user_spec.rb:6 # User rspec ./spec/models/user_spec.rb:9 # User creates an user Randomized with seed 10444
@jlucasps # -*- coding: utf-8 -*- require 'spec_helper' describe User do it { should allow_mass_assignment_of :name } it { should allow_mass_assignment_of :email } it "creates an user" do user = User.new(:name => "João Lucas", :email => "[email protected]", : age => 24) user.save.should be_true end it "fail to create a user when name is blank" do user = User.new(:email => "[email protected]", :age => 24) user.save.should be_false end it "fail to create a user when email is blank" do user = User.new(:name => "João Lucas", :age => 24) user.save.should be_false end end
fail to create a user when name is blank Failure/Error: user.save.should be_false expected: false value got: true # ./spec/models/user_spec.rb:16:in `block (2 levels) in <top (required)>' 2) User fail to create a user when email is blank Failure/Error: user.save.should be_false expected: false value got: true # ./spec/models/user_spec.rb:21:in `block (2 levels) in <top (required)>' Finished in 0.37949 seconds 9 examples, 2 failures Failed examples: rspec ./spec/models/user_spec.rb:14 # User fail to create a user when name is blank rspec ./spec/models/user_spec.rb:19 # User fail to create a user when email is blank Randomized with seed 46469
......... Finished in 0.50004 seconds 9 examples, 0 failures Randomized with seed 2195 $ git status $ git add . $ git commit -m "Não permitir que sejam criados usuários com nome ou email em branco."
'spec_helper' describe User do ................... ................... it "creates a user with gender value MALE" do user = User.new(:name => "Bob Dylan", :email => "bob@dylan. com", :age => 72, :gender => User::MALE) user.save.should be_true end it "creates a user with gender value FEMALE" do user = User.new(:name => "Candice Swanepoel", :email => "[email protected]", :age => 24, :gender => User::FEMALE) user.save.should be_true end end
fail to create a user with gender value MALE Failure/Error: user = User.new(:name => "Bob Dylan", :email => "[email protected]", :age => 72, :gender => User::MALE) NameError: uninitialized constant User::MALE # ./spec/models/user_spec.rb:25:in `block (2 levels) in <top (required)>' 2) User fail to create a user with gender value FEMALE Failure/Error: user = User.new(:name => "Candice Swanepoel", :email => "[email protected]", :age => 24, :gender => User::FEMALE) NameError: uninitialized constant User::FEMALE # ./spec/models/user_spec.rb:30:in `block (2 levels) in <top (required)>' Finished in 0.38009 seconds 11 examples, 2 failures Failed examples: rspec ./spec/models/user_spec.rb:24 # User fail to create a user with gender value MALE rspec ./spec/models/user_spec.rb:29 # User fail to create a user with gender value FEMALE Randomized with seed 23755
caso a idade seja maior ou igual a 18? @jlucasps context "when age >= 18" do it "creates an user with gender value" do user = User.new(:name => "João Lucas", :email => "[email protected]", :age => 18, : gender => User::MALE) user.save.should be_true end it "does not create an user without gender value" do user = User.new(:name => "João Lucas", :email => "[email protected]", :age => 18) user.save.should be_false end end context "when age < 18" do it "creates an user with gender value" do user = User.new(:name => "João Lucas", :email => "[email protected]", :age => 17, : gender => User::MALE) user.save.should be_true end it "does not create an user without gender value" do user = User.new(:name => "João Lucas", :email => "[email protected]", :age => 17) user.save.should be_true end end
when age >= 18 does not create an user without gender value Failure/Error: user.save.should be_false expected: false value got: true # ./spec/models/user_spec.rb:48:in `block (3 levels) in <top (required)>' Finished in 0.40493 seconds 16 examples, 1 failure Failed examples: rspec ./spec/models/user_spec.rb:46 # User when age >= 18 does not create an user without gender value
0.40208 seconds 16 examples, 0 failures Randomized with seed 46088 $ git status $ git add . $ git commit -m "Necessário informar o sexo caso a idade seja maior ou igual a 18."
não seja possível o cadastro de dois usuários com o mesmo email. Vale lembrar que, além da validação no modelo, podemos também implementar uma validação no banco de dados para garantir unicidade de uma coluna. No entanto, primeiro, vamos aos testes.
nossa suite de testes e executar $ rspec context "when tries to create two users with same email" do it "create two users with differente emails" do user_1 = User.create(:name => "Primeiro usuário", :email => "[email protected]") user_2 = User.new(:name => "Segundo usuário", :email => "[email protected]") user_2.save.should be_true end it "does no create two users with same emails" do user_1 = User.create(:name => "Primeiro usuário", :email => "[email protected]") user_2 = User.new(:name => "Segundo usuário", :email => "[email protected]") user_2.save.should be_false end end
que não esperávamos 1) User when tries to create two users with same email create two users with differente emails Failure/Error: user_1 = User.create(:name => "Primeiro usuário", :email => "[email protected]") NoMethodError: undefined method `>=' for nil:NilClass # ./app/models/user.rb:21:in `adulthood' # ./spec/models/user_spec.rb:68:in `block (3 levels) in <top (required)>' 2) User when tries to create two users with same email does no create two users with same emails Failure/Error: user_1 = User.create(:name => "Primeiro usuário", :email => "[email protected]") NoMethodError: undefined method `>=' for nil:NilClass # ./app/models/user.rb:21:in `adulthood' # ./spec/models/user_spec.rb:74:in `block (3 levels) in <top (required)>'
Vamos implementar alguns testes para o método adulthood, verificar os erros e atualizar o código describe "#adulthood" do it "is adult when age == 18" do user = User.new(:name => "Nome", :email => "[email protected]", :age => 18) user.adulthood.should be_true end it "is adult when age > 18" do user = User.new(:name => "Nome", :email => "[email protected]", :age => 30) user.adulthood.should be_true end it "is not adult when age < 18" do user = User.new(:name => "Nome", :email => "[email protected]", :age => 17) user.adulthood.should be_false end it "is not adult when age is blank" do user = User.new(:name => "Nome", :email => "[email protected]") user.adulthood.should be_false end end
when tries to create two users with same email does no create two users with same emails Failure/Error: user_2.save.should be_false expected: false value got: true # ./spec/models/user_spec.rb:76:in `block (3 levels) in <top (required)>' Finished in 0.40533 seconds 22 examples, 1 failure Failed examples: rspec ./spec/models/user_spec.rb:73 # User when tries to create two users with same email does no create two users with same emails Randomized with seed 45305 Agora sim, encontramos o erro esperado na criação de dois usuários com mesmo email.