我正在尝试使用默认的rails测试框架编写一些基本的Rails测试代码。我的应用程序是一个简单的论坛,用户可以发布帖子,评论等。
我试图测试论坛(即一个线程)控制器,这里是: 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".
不确定您是否需要查看我的迁移文件,但如果您需要任何其他信息,请告诉我们。
我会很感激任何建议。
谢谢
注意:我正在使用devise gem进行用户身份验证。这也用于生成users表。
我认为表的结构存在问题,用户不会有user_id列而只有id,如果其他模型有一个User,或者属于User,那么该模型将有一个user_id列来获取相应的用户。查看doc以了解数据库中必须具有的结构:http://guides.rubyonrails.org/association_basics.html
我设法解决了这个问题,首先遵循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
为什么你不使用Rails灯具的全部功率:
-----comments.yml----
comm_one:
body: MyText
forum: for_one
comm_two:
body: MyText
forum: for_two
---- forums.yml-----
for_one:
title: MyString
body: MyText
user: user_one
for_two:
title: MyString
body: MyText
user: user_two
----- users.yml -----
user_one:
email: '[email protected]'
user_two:
email: '[email protected]'