2014-10-28 129 views
0

我是Ruby on Rails中一个初学者(英文:)),我尝试使用功能测试,但我在拳功能测试:NomethodError

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:我的应用程序仍然在本地主机

+1

'current_user'返回'nil'。 – 2014-10-28 10:30:33

+0

@mayoneQD你在控制器中提到'current_user',但是在测试控制器规范中你没有指定任何用户,所以它是空的尝试在执行测试之前定义'user' – anusha 2014-10-28 10:53:12

+0

@anusha谢谢,我理解,但是我试图设置用户=用户(:一),但它没有工作 – mayoneQD 2014-10-29 02:33:46

回答

1

工作,如果你正在使用设计用户认证,那么你需要进行身份验证,并在您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

没有完成它

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

+0

你的答案是relly帮助,我可以学到更多,虽然它现在不工作,但我认为我应该更努力地找出:) – mayoneQD 2014-10-29 02:57:54