首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >功能测试: NomethodError

功能测试: NomethodError
EN

Stack Overflow用户
提问于 2014-10-28 10:29:14
回答 1查看 143关注 0票数 0

我是rails(和英语:)的初学者,我正在尝试使用函数测试,但我一开始就出错了

代码语言:javascript
复制
1)Error:
test_should_get_new(MicropostControllerTest)
NoMethodError: undefined method 'microposts' for nil:NilClass

我的micropost_controller_test.rb

代码语言:javascript
复制
require 'test_helper'
class MicropostControllerTest < ActionController::TestCase
  test "should get new" do
    get :new
    assert_response :success
  end
end

我的micropost_controller.rb

代码语言:javascript
复制
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:我的应用程序仍然在本地主机上工作。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-10-28 11:12:25

如果您正在使用设计进行用户身份验证,那么您需要在MicropostController中进行身份验证和设置current_user,例如,拥有一个before_action,如下所示:

代码语言:javascript
复制
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中这样做,则需要按以下方式导入设计测试帮助程序

代码语言:javascript
复制
class MicropostControllerTest < ActionController::TestCase
 include Devise::TestHelpers
end

然后,您可以使用sign_in方法在测试中使用固定装置在用户中签名。搜索一些关于这方面的教程,或者查看这里的响应,以获得一些线索:Functional testing with Rails and Devise. What to put in my fixtures?

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26605986

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档