【问题标题】:rails initialize methode in model or controller? Rails Test Error模型或控制器中的rails初始化方法? Rails 测试错误
【发布时间】: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


    【解决方案1】:

    您在迁移中为“pername”使用了 db 约束(null: false)。 因此,当您在测试中调用 stud.save 时出现错误,因为您的 stud 正在尝试使用空白 pername 字段将 stud 记录保存在 db 中。也许,最好使用 valid? insted of save :)

    【讨论】:

    • 感谢帮助,但是当我测试这样的东西时:test "hello" do stud = Student.new stud.prename = "Gustav" stud.lastname = "Meyer" stud.birthday = "30.05 .1992".to_date stud.add_to_form(3,"A") assert stud.save end 我得到完全相同的错误
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多