初始化没有参数的类时ActiveModel :: Model错误

时间:2016-08-20 08:31:19

标签: ruby-on-rails ruby-on-rails-5

运行测试时,如果我尝试使用User.new创建新对象,则会出错。如果我使用User.new({}),它可以正常工作。

如果没有传入,那么它们是否应该默认为空?

$ rails -v

Rails 5.0.0.1

user.rb

class User
  include ActiveModel::Model

  attr_accessor :name, :email, :country
end

user_test.rb

require 'test_helper'
class User < ActiveSupport::TestCase

  test "should create an empty user when initialized with no params" do
    user = User.new
    assert_not_nil(user, 'user cannot be empty')
  end
end

测试结果

Error:
User#test_should_create_an_empty_user_when_initialized_with_no_parameters:
ArgumentError: wrong number of arguments (given 0, expected 1)
    test/models/user_test.rb:7:in `new'
    test/models/user_test.rb:7:in `block in <class:User>'

3 个答案:

答案 0 :(得分:0)

通常,attr_accessor在模型上用于SQL表中不是实际列的列。

因此,如果您的模型包含:name:email:country列,则无需声明attr_accessor。我认为rails现在正在等你宣布它们。

尝试评论attr_accessor :name, :email, :country行,然后重新运行测试。

答案 1 :(得分:0)

这可能会有所帮助

而不是将模型类扩展为:

class Crime < ApplicationRecord
 //do your stuff here
end

然后你可以使用@user = User.new

答案 2 :(得分:0)

您在测试中引用的User是测试本身。

最简单的解决方案是遵循Ruby约定并命名测试类UserTest