homior
homior

Reputation: 191

rails initialize methode in model or controller? Rails Test Error

I'm new to Ruby on Rails and I'm working at my first project. I'm not a native english speaker, so I failed looking up at google. First I would like to know, if u declare a initialize method, for a Class like:

def initialize(attributes = {})
@name = attributes[:name]
@email = attributes[:email]
end

Or like:

class Person
 def initialize(name, age)
  @name, @age = name, age
 end
end

Do i have to delcare that method in the controller or in the model of the corresponding Class?

Is it true that we use instance Variables (@name or @age) just in the Controller? The intance Variables for our models we declare in the migration files right? like:

class CreateStudents < ActiveRecord::Migration
 def up
  create_table :students do |t|
   t.string :prename, :limit => 100, :null=>false
   t.string :lastname, :limit => 100, :null=>false
   t.date :birthday, :null => false
   t.text :contact
   t.boolean :daz, :null => false, :default => false
   t.integer :form_id

   t.timestamps null: false
 end
end

def down
 drop_table :students
end

end

My last question is about the Test files in rails. I read something like this: require 'test_helper'

class StudentTest < ActiveSupport::TestCase
  test "hello" do
    stud = Student.new
    assert_not stud.save
  end
end

When i run "rake test", it got this Error:

yannick@Yannux ~/SchulDatenbank $ rake test
Running via Spring preloader in process 5041
Run options: --seed 16904

# Running:

E

Finished in 0.032498s, 30.7711 runs/s, 0.0000 assertions/s.

  1) Error:
StudentTest#test_hello:
ActiveRecord::StatementInvalid: SQLite3::ConstraintException: 
NOT NULL constraint failed: students.prename: INSERT INTO 
"students" ("created_at", "updated_at", "id") VALUES 
('2017-03-18 14:04:40', '2017-03-18 14:04:40', 980190962)


1 runs, 0 assertions, 0 failures, 1 errors, 0 skips

then i tried something like: require 'test_helper'

class StudentTest < ActiveSupport::TestCase
  test "hello" do
    assert true
  end
end

Same Error... Does anyone know why? :) Thank u for help

Upvotes: 0

Views: 568

Answers (1)

Ruslan Kornienko
Ruslan Kornienko

Reputation: 261

You are using db constraint in your migration for "pername" (null: false). Therefore, you got error when you call stud.save in your test, because your stud is trying to save stud record in db with blank pername field. Maybe, would be better to use valid? insted of save :)

Upvotes: 0

Related Questions