我正在根据Hartl教程创建一个应用程序,并且我坚持第二个练习:
为所有布局链接编写集成测试,包括登录和未登录用户的正确行为。提示:使用log_in_as帮助程序添加到代码清单5.25中的测试。
我测试中的代码是
require 'test_helper'
class SiteLayoutTest < ActionDispatch::IntegrationTest
def setup
@user = users(:test)
end
test 'layout links' do
get root_path
assert_template 'static_pages/home'
assert_select "a[href=?]", root_path, count: 2
assert_select "a[href=?]", help_path
assert_select "a[href=?]", about_path
assert_select "a[href=?]", contact_path
assert_select "a[href=?]", login_path
get signup_path
assert_select "title", full_title("Signup")
log_in_as @user
get root_path
assert_select "a[href=?]", users_path, text: "Users"
assert_select "a[href=?]", user_path
assert_select "a[href=?]", edit_user_path(@user)
assert_select "a[href=?]", logout_path
端 端
这是我正在使用的灯具:
test:
name: Test Name
derby_name: Test Derby Name
email: test@rdsg.com
password_digest: <%= User.digest('password') %>
admin: true
这是我在进行测试时遇到的错误:
ERROR["test_layout_links", SiteLayoutTest, 2015-07-07 21:08:39 +0000]
test_layout_links#SiteLayoutTest (1436303319.87s)
ActionController::UrlGenerationError: ActionController::UrlGenerationError: No route matches {:action=>"show", :controller=
>"users"} missing required keys: [:id]
test/integration/site_layout_test.rb:22:in `block in <class:SiteLayoutTest>'
test/integration/site_layout_test.rb:22:in `block in <class:SiteLayoutTest>'
在我看来,我的灯具由于某种原因没有生成ID,即使我手动运行测试时我也能正常访问站点导航URL,当我运行rails console --sandbox并创建一个新用户时对象它生成一个ID。我已经尝试过寻找答案,但没有运气(我已经坚持了好几天了!)。
我正在使用带有Rails 4.2.0的Codio IDE和带有Minitest的Ruby 2.1.5作为测试套件。
编辑:作为参考,这是我的log_in_as助手:
# Logs in a test user
def log_in_as(user, options = {})
password = options[:password] || 'password'
remember_me = options[:remember_me] || '1'
if integration_test?
post login_path, session: { email: user.email,
password: password,
remember_me: remember_me }
else
session[:user_id] = user.id
end
end
以防将来帮助任何人:)
谢谢,Baldrick,在下面解决它!
答案 0 :(得分:1)
错误消息的重要部分是ActionController::UrlGenerationError: No route matches {:action=>"show", :controller=>"users"} missing required keys: [:id]
。方法user_path
需要一个用户(它是显示给定用户的路径),所以它应该是
assert_select "a[href=?]", user_path(@user)