2017-11-25 246 views
0

我想寫一些基本的Rails測試代碼,使用默認的軌道測試框架。我的應用程序是一個簡單的論壇,在這裏用戶可以發佈主題,發表評論等紅寶石軌道測試 - 表X沒有列名爲Y

我試圖測試論壇(即線程)控制器,那就是:

forums_controller_test.rb

require 'test_helper' 

class ForumsControllerTest < ActionController::TestCase 
test "index should be success" do 
    get :index 
    assert_response :success 
end 
end 

我使用的夾具和我下面這個教程: https://www.youtube.com/watch?v=0wIta0fITzc

這裏是我所有的測試數據中:

comments.yml

comm_one: 
    body: MyText 
    forum_id: 1 

comm_two: 
    body: MyText 
    forum_id: 2 

forums.yml

for_one: 
    title: MyString 
    body: MyText 
    user_id: 1 

for_two: 
    title: MyString 
    body: MyText 
    user_id: 2 

users.yml裏

user_one: 
    user_id: '1' 

user_two: 
    user_id: '2' 

我遇到的問題是,當我在終端運行rake,我得到這個錯誤:

Error: ForumsControllerTest#test_index_should_be_success: ActiveRecord::Fixture::FixtureError: table "users" has no column named "user_id".

不知道您是否需要查看我的遷移文件,但是如果您需要任何其他信息,請告訴我。

我將不勝感激任何意見。

感謝

注:我使用的是色器件寶石爲我的用戶認證。這也用於生成用戶表。

回答

1

我認爲在表中有一個問題,用戶不會有一個user_id列,而只是一個id,如果另一個模型有一個用戶,或者屬於一個用戶,那麼該模型將有一個user_id列來獲取相應的用戶。 看看文檔,以瞭解您的數據庫中必須具有的結構:http://guides.rubyonrails.org/association_basics.html

+1

謝謝你,我改變了,USER_ID ID,而且這導致我解決了這個問題(解決了其他一些問題之後) – User59

1

我設法解決這個問題,首先遵循Tisamu關於用id替換user_id的建議。然後我添加用戶電子郵件到用戶文件,使其如此:

user_one: 
    id: 1 
    email: '[email protected]' 

user_two: 
    id: 2 
    email: '[email protected]' 

這解決了與任何代碼的問題。但我後來接到錯誤消息說此:

Error: 
ForumsControllerTest#test_index_should_be_success: 
ActionView::Template::Error: Devise could not find the `Warden::Proxy` instance on your request environment. 
Make sure that your application is loading Devise and Warden as expected and that the `Warden::Manager` middleware is present in your middleware stack. 
If you are seeing this on one of your tests, ensure that your tests are either executing the Rails middleware stack or that your tests are using the `Devise::Test::ControllerHelpers` module to inject the `request.env['warden']` object for you. 
    app/views/forums/index.html.erb:21:in `block in _app_views_forums_index_html_erb___3974819143402431947_37087120' 
    app/views/forums/index.html.erb:15:in `_app_views_forums_index_html_erb___3974819143402431947_37087120' 
    test/controllers/forums_controller_test.rb:6:in `block in <class:ForumsControllerTest>' 

我通過簡單地添加Devise::Test::ControllerHelpers我的測試文件解決了這個問題,使之像這樣:

require 'test_helper' 

class ForumsControllerTest < ActionController::TestCase 
include Devise::Test::ControllerHelpers # <-- Have to include this 
test "index should be success" do 
    get :index 
    assert_response :success 
end 
end