功能测试:命名方法错误



我是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里放些东西,但没用。那么,我在哪里可以找到功能测试的微柱方法,我该如何解决??请帮帮我?

p/s:我的应用程序仍然可以在localhost 中工作

如果您使用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登录用户。搜索一些关于这方面的教程,或者查看这里的回复以获得一些线索:使用Rails和Devise进行功能测试。在我的固定装置里放什么?

最新更新