Rails模型测试抛出的错误似乎应该是另一个模型

时间:2015-06-22 15:17:07

标签: ruby-on-rails ruby unit-testing ruby-on-rails-4

以下是我先获得的错误:

1) Error:
ReservationTest#test_should_be_valid:
ActiveRecord::StatementInvalid: SQLite3::ConstraintException: NOT NULL constraint failed: contacts.created_at: INSERT INTO "contacts" ("name", "email", "message", "nickname") VALUES ('MyText', NULL, 'MyText', 'MyText')

所以我尝试使用名为" Reservation"的模型测试表单,这里是代码:

class Reservation < ActiveRecord::Base
  attribute :group_name,      :validate => true
  attribute :contact_email,     :validate => /\A([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})\z/i
  attribute :date,      :validate => true
  attribute :groupsize, :validate => true
end

该模型的测试是:

require 'test_helper'

class ReservationTest < ActiveSupport::TestCase

  def setup
    @reservation = Reservation.new(group_name: "Example", contact_email: "user@example.com", date: "06/20/2015", groupsize: "4")
  end

  test "should be valid" do
    assert @reservation.valid?
  end
end

它应该引用的表在模式中。

ActiveRecord::Schema.define(version: 20150620202043) do

  create_table "contacts", force: :cascade do |t|
    t.text     "name"
    t.text     "email"
    t.text     "message"
    t.text     "nickname"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "reservations", force: :cascade do |t|
    t.string   "group_name"
    t.string   "contact_email"
    t.datetime "date"
    t.integer  "table"
    t.integer  "groupsize"
    t.datetime "created_at",    null: false
    t.datetime "updated_at",    null: false
  end

  create_table "users", force: :cascade do |t|
    t.datetime "created_at",                          null: false
    t.datetime "updated_at",                          null: false
    t.string   "email",                  default: "", null: false
    t.string   "encrypted_password",     default: "", null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0,  null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
  end

  add_index "users", ["email"], name: "index_users_on_email", unique: true
  add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true

end

我确定我忽略了一些非常简单的事情。谢谢你的帮助。

编辑:我刚刚意识到它可以帮助您查看我的联系人模型。

class Contact < MailForm::Base
  attribute :name,      :validate => true
  attribute :email,     :validate => /\A([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})\z/i
  attribute :message
  attribute :nickname,  :captcha  => true

  # Declare the e-mail headers. It accepts anything the mail method
  # in ActionMailer accepts.
  def headers
    {
      :subject => "Wiltshire Pub Inquiry",
      :to => "some-name@gmail.com",
      :from => %("#{name}" <#{email}>)
    }
  end
end

0 个答案:

没有答案