【发布时间】:2017-03-18 23:33:29
【问题描述】:
我是 Ruby on Rails 的新手,我正在从事我的第一个项目。我不是以英语为母语的人,所以我没能抬头看谷歌。首先我想知道,如果你声明一个初始化方法,对于像这样的类:
def initialize(attributes = {})
@name = attributes[:name]
@email = attributes[:email]
end
或者喜欢:
class Person
def initialize(name, age)
@name, @age = name, age
end
end
我必须在控制器或相应类的模型中删除该方法吗?
我们在控制器中使用实例变量(@name 或@age)是真的吗?我们在迁移文件中声明的模型的实例变量对吗?喜欢:
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
结束
我的最后一个问题是关于 Rails 中的测试文件。 我读到这样的东西: 需要'test_helper'
class StudentTest < ActiveSupport::TestCase
test "hello" do
stud = Student.new
assert_not stud.save
end
end
当我运行“rake test”时,它得到了这个错误:
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
然后我尝试了类似的方法: 需要'test_helper'
class StudentTest < ActiveSupport::TestCase
test "hello" do
assert true
end
end
同样的错误... 有谁知道为什么? :) 谢谢你的帮助
【问题讨论】:
标签: ruby-on-rails ruby testing model initialization