2016-08-20 27 views
1

運行測試時,如果嘗試使用User.new創建新對象,則出現錯誤。如果相反,我使用User.new({}),它工作正常。ActiveModel ::初始化沒有參數的類時出現的模型錯誤

如果沒有傳入,params是否應該默認爲空?

$ 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>' 
+0

當您在Rail控制檯中執行User.new時會發生什麼?你在user.rb中有初始化方法嗎? – margo

+0

你確定'test'中的'User'是用戶*模型*而不是用戶*測試*? –

+0

有時,你只需要有人指出明顯的,謝謝@DaveNewton – pameck

回答

0

一般來說,attr_accessor上的模型用於不在SQL表的實際列列。

因此,如果您的模型有:name,:email:country列,則聲明attr_accessor是不必要的。我認爲鐵軌正在等待你現在宣佈他們。

嘗試註釋掉attr_accessor :name, :email, :country一行,然後重新運行測試。

+0

感謝您的快速反應,我試圖取消它的註釋,但沒有奏效。 無論如何,'attr_accessor'只是給getter和setter類的Ruby方法。根據[ActiveModel :: Model doc](http://api.rubyonrails.org/classes/ActiveModel/Model.html) – pameck

0

這可能有助於

而是包括模型類擴展它喜歡:

class Crime < ApplicationRecord 
//do your stuff here 
end 

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

+0

這似乎不是一個問題。這只是一個錯誤,命名測試完全像該模型。 將測試名稱從'User'更改爲'UserTest',並且它都是固定的。 謝謝你的迴應! – pameck

0

User你在引用測試本身就是測試。

最簡單的解決方案是遵循Ruby約定並命名測試類UserTest

+0

不時,你只需要有人指出明顯的,謝謝。 – pameck

相關問題