【问题标题】:functional test: NomethodError功能测试:NomethodError
【发布时间】:2014-12-23 17:15:36
【问题描述】:

我是 ruby​​ on rails 的初学者(和英语:)),我正在尝试使用功能测试,但我的拳头出错了

1)Error:
test_should_get_new(MicropostControllerTest)
NoMethodError: undefined method 'microposts' for nil:NilClass

我的 micropost_controller_test.rb

require 'test_helper'
class MicropostControllerTest < ActionController::TestCase
  test "should get new" do
    get :new
    assert_response :success
  end
end

我的 micropost_controller.rb

class MicropostController < ApplicationController
  def new
    @post = Micropost.new
    @posts = current_user.microposts.all
  end
  def create
    @post = current_user.microposts.create(:content => params[:content])
    logger.debug "New post: #{@post.attributes.inspect}"
    logger.debug "Post should be valid: #{@post.valid?}"
    if @post
    redirect_to micropost_new_path
    else
  end
  end
end

我尝试在 microposts.yml 中添加一些内容,但没有成功。 那么,我在哪里可以找到用于功能测试的 microposts 方法,我该如何解决?请帮帮我?

p/s:我的应用仍然在本地主机中运行

【问题讨论】:

  • current_user 返回nil。
  • @mayoneQD 您在控制器中提到了current_user,但在测试控制器规范中您没有指定任何用户,因此在执行测试之前尝试定义user 为空
  • @anusha 谢谢,我明白了,但是我如何让用户进入控制器测试,我尝试设置 user = users(:one) 但它没有用
  • @mayoneQD 如果您使用devise 进行身份验证,请尝试遵循@Alireza 的回答
  • 我发现了,我只是把我的助手放在controller_test中,然后我就可以正常登录用户了:)

标签: ruby-on-rails ruby


【解决方案1】:

如果您使用 Devise 进行用户身份验证,那么您需要在您的MicropostController 中进行身份验证并设置current_user,例如使用before_action,如下所示:

class MicropostController < ApplicationController
  before_action :authenticate_user!

  def new
    @post = Micropost.new
    @posts = current_user.microposts.all
  end
# rest of the code
end

在您的测试中,如果您还没有在test_helper 中这样做,您需要按如下方式导入设计测试助手

class MicropostControllerTest < ActionController::TestCase
 include Devise::TestHelpers
end

然后,您可以使用 sign_in 方法在您的测试中使用 Fixtures 登录用户。搜索一些教程或查看这里的回复以获得一些线索:Functional testing with Rails and Devise. What to put in my fixtures?

【讨论】:

  • 你的回答是非常有帮助的,我可以学到更多,虽然它现在不起作用,但我认为我应该更加努力地找出:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多