【问题标题】:Why i can not get current_user while writing test case with Rspec and Capybara为什么在使用 Rspec 和 Capybara 编写测试用例时无法获取 current_user
【发布时间】:2012-04-06 04:49:21
【问题描述】:

我必须为我的一个功能列表页面编写集成测试用例,并且该功能索引方法具有如下代码

def index
  @food_categories = current_user.food_categories
end

现在,当我尝试为此编写测试用例时,它会引发错误

'undefined method features for nil class' because it can not get the current user

现在我要做的如下 我在每条语句之前写了登录过程,然后写了功能列表页面的测试用例

您能告诉我如何获得current_user 吗?

仅供参考,我使用了 devise gem 并使用 Rspec 进行集成测试用例

这里是my spec file 这是我的food_categories_spec.rb

【问题讨论】:

  • 嘿@chirag.sweng,您可能想要交换您提供的链接的名称。 spec_helper 文件指向 foot_categories_spec 文件,反之亦然。真的只是一个注释。这是我的规范文件这是我的 food_categories_spec.rb

标签: ruby-on-rails rspec devise integration-testing capybara


【解决方案1】:

更新:您混淆了功能测试和集成测试。集成测试不使用get,因为没有要测试的控制器操作,而是必须使用visit(一些url)。然后您必须检查页面的内容,而不是响应代码(后者用于功能测试)。它可能看起来像:

visit '/food_categories'
page.should have_content 'Eggs'
page.should have_content 'Fats and oils'

如果您需要功能测试,这里有一个例子:

# spec/controllers/your_controller_spec.rb
describe YourController do

  before do
    @user = FactoryGirl.create(:user)
    sign_in @user
  end

  describe "GET index" do

    before do
      get :index
    end

    it "is successful" do
      response.should be_success
    end

    it "assings user features" do
      assigns(:features).should == @user.features
    end
  end
end

# spec/spec_helper.rb
RSpec.configure do |config|
  #...
  config.include Devise::TestHelpers, :type => :controller
end

【讨论】:

  • 谢谢,但现在它为#<:core::examplegroup::nested_1::nested_1:0xa95fa38> 抛出错误未定义方法`sign_in',如果您有任何想法,请告诉我
  • 仅供参考,我正在编写集成测试用例
  • 是的,感谢您的快速回复,但我已经在我的 spec_helper.rb 中添加了,你想让我给你看一下我的 spec_helper.rb 文件吗?
  • @chirag.sweng spec_helper 和规范你有问题将是最低限度的。始终尽可能多地提供有问题的信息。
  • @chirag.sweng 我错过了你关于集成测试的评论(你应该注意这个问题!)。你确定你需要集成测试吗?分配仅在功能测试中进行测试 (spec/controllers)。进行集成测试是为了确保特定链接、按钮和其他 HTML 元素位于页面上,并且您可以与它们进行交互。
猜你喜欢
  • 2014-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多