3

我对尝试对我拥有的模型(用户)进行单元测试时出现的错误感到非常困惑。我在 test/fixtures/users.yml 中有一个模型的夹具

new_user_in_unavailable_country:
  first_name: John
  last_name: Lennon
  email: john.lennon@pop.co.uk
  password: YokoOn0
  country: UNITED KINGDOM

现在在 test/unit/user_test.rb 我有

require 'test_helper'

class UserTest < ActiveSupport::TestCase
  test "status_auto_fill_for_unavailable_country" do
     users(:new_user_in_unavailable_country).valid?
     assert users(:new_user_in_unavailable_country).status == "SUBSCRIBED"
  end
end

到目前为止,一切都很好。现在,这是在 rake:test:units 上生成的:

 Error:
test_status_auto_fill_for_available_country(UserTest):
ActiveRecord::StatementInvalid: Mysql2::Error: Field 'name' doesn't have a default value: INSERT INTO `countries` (`id`) VALUES (980190962)

好的,如果在表格国家的某个地方有一个隐藏的插入(我从来没有要求过!),我应该能够在 Rails 控制台中运行相同的代码时看到它。所以我尝试了:

> usr = User.new(:first_name => "John", :last_name => "Lennon", :email => "john.lennon@pop.co.uk", :password => "YokoOn0", :country => "UNITED KINGDOM")
#<User id: nil, first_name: "John", last_name: "Lennon", email: "john.lennon@pop.co.uk", hashed_password: nil, password_salt: nil, created_at: nil, updated_at: nil, organization_id: nil, country: "UNITED KINGDOM", status: nil>

>> usr.valid?
   (1.0ms)  SELECT COUNT(*) FROM `countries` WHERE `countries`.`available` = 1 AND `countries`.`name` = 'UNITED KINGDOM'
   (1.0ms)  SELECT COUNT(*) FROM `countries` WHERE `countries`.`available` = 1 AND `countries`.`name` = 'UNITED KINGDOM'
   (0.0ms)  SELECT COUNT(*) FROM `countries` WHERE `countries`.`available` = 1 AND `countries`.`name` = 'UNITED KINGDOM'
   (1.0ms)  SELECT COUNT(*) FROM `countries` WHERE `countries`.`available` = 1 AND `countries`.`name` = 'UNITED KINGDOM'
   (0.0ms)  SELECT COUNT(*) FROM `countries` WHERE `countries`.`available` = 1 AND `countries`.`name` = 'UNITED KINGDOM'
   (0.0ms)  SELECT COUNT(*) FROM `countries` WHERE `countries`.`available` = 1 AND `countries`.`name` = 'UNITED KINGDOM'
   (0.0ms)  SELECT COUNT(*) FROM `countries` WHERE `countries`.`available` = 1 AND `countries`.`name` = 'UNITED KINGDOM'
   (0.0ms)  SELECT COUNT(*) FROM `countries` WHERE `countries`.`available` = 1 AND `countries`.`name` = 'UNITED KINGDOM'
   (0.0ms)  SELECT COUNT(*) FROM `countries` WHERE `countries`.`available` = 1 AND `countries`.`name` = 'UNITED KINGDOM'
  User Exists (1.0ms)  SELECT 1 FROM `users` WHERE `users`.`email` = BINARY 'john.lennon@pop.co.uk' LIMIT 1
true

>> usr.status
"SUBSCRIBED"

好的,没有插入国家表。

知道我失踪并产生此错误的幕后发生了什么吗?

Create Country migration:
class CreateCountries < ActiveRecord::Migration
  def change
     create_table :countries do |t|
      t.string      :name , :null => false
      t.string      :iso_2_letters_code , :null => false
      t.string      :iso_3_letters_code , :null => false
      t.integer     :phone_code
    end

    add_index :countries , :iso_2_letters_code , :unique => true
    add_index :countries , :iso_3_letters_code , :unique => true
  end
end
4

0 回答 0