Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/neo4j/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 功能测试:NomethodError_Ruby On Rails_Ruby - Fatal编程技术网

Ruby on rails 功能测试:NomethodError

Ruby on rails 功能测试:NomethodError,ruby-on-rails,ruby,Ruby On Rails,Ruby,我是RubyonRails的初学者(英文:),我正在尝试使用FunctionalTest,但一开始就出现了一个错误 1)Error: test_should_get_new(MicropostControllerTest) NoMethodError: undefined method 'microposts' for nil:NilClass 我的micropost\u控制器\u test.rb require 'test_helper' class MicropostControllerT

我是RubyonRails的初学者(英文:),我正在尝试使用FunctionalTest,但一开始就出现了一个错误

1)Error:
test_should_get_new(MicropostControllerTest)
NoMethodError: undefined method 'microposts' for nil:NilClass
我的micropost\u控制器\u test.rb

require 'test_helper'
class MicropostControllerTest < ActionController::TestCase
  test "should get new" do
    get :new
    assert_response :success
  end
end
需要“测试助手”
类MicropostControllerTest
My 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
class MicropostControllerparams[:content])
logger.debug“新帖子:#{@post.attributes.inspect}”
logger.debug“Post应该有效:#{@Post.valid?}”
如果@post
重定向到micropost\u新路径
其他的
结束
结束
结束
我试着在microposts.yml里放些东西,但没用。 那么,我在哪里可以找到功能测试的microposts方法?我该如何解决这个问题??请帮帮我


p/s:My app仍然可以在本地主机上运行

如果您正在使用设计进行用户身份验证,那么您需要在
MicropostController
中进行身份验证并设置
当前用户
,例如在执行操作之前设置一个
,如下所示:

class MicropostController < ApplicationController
  before_action :authenticate_user!

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

然后,您可以使用
sign_in
方法在测试中使用fixture登录用户。搜索一些关于这方面的教程或检查此处的响应以获得一些线索:

current\u user
返回
nil
@mayoneQD您在控制器中提到了
current\u user
,但在测试控制器规范中,您没有指定任何用户,因此它是空的。请在执行测试之前尝试定义
user
test@anusha 谢谢你们,我明白了,但我如何将用户放入控制器测试,我尝试设置user=users(:1),但它没有work@mayoneQD尝试按照@Alireza的答案进行操作如果您正在使用
designe
进行身份验证我发现,我刚刚将我的助手放入控制器测试,然后我可以正常登录用户:)您的答案非常有帮助,我可以学到更多,虽然现在不起作用,但我想我应该更努力地去发现:)
class MicropostControllerTest < ActionController::TestCase
 include Devise::TestHelpers
end