测试失败:关联ID应该是必需的

时间:2015-07-24 16:18:11

标签: ruby-on-rails ruby testing associations integration-testing

我有以下集成测试:

def setup
  @file = fixture_file_upload('test/fixtures/rails.jpg')
  @user = users(:one)
  @image = @user.build_image(image_file: @file)
end

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

test "image_file should be present" do
  @image.image_file = "     "
  assert_not @image.valid?
end

test "user_id should be present" do
  @image.user_id = "     "
  assert_not @image.valid?
end

最后一次集成测试失败 - 即@image有效 - 我不明白。鉴于下面的迁移文件,user_id不应该是强制性的?

def change
  create_table :images do |t|
    t.references :user, index: true, foreign_key: true
    t.string :image_file, null: false

    t.timestamps null: false
  end
end

1 个答案:

答案 0 :(得分:1)

.valid?仅检查您的模型中的验证,而不是您的架构。您需要做的是在图像模型中添加验证

class Image < ActiveRecord::Base
  validates :user, presence: true
end

以及您可能想要使用的任何其他验证。