为什么在使用Rspec和Capybara编写测试用例时无法获取current_user [英] Why i can not get current_user while writing test case with Rspec and Capybara

查看:189
本文介绍了为什么在使用Rspec和Capybara编写测试用例时无法获取current_user的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须为我的一个功能列表页面写入集成测试用例,该特征索引方法的代码如下所示

I have to write integration test case for my one feature listing page and that feature index method has code like below

def index
  @food_categories = current_user.food_categories
end

现在,当我尝试为此写一个测试用例它抛出一个错误

Now when i try to write a test case for this it throws an error

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

现在我所做的是在
以下我已经在前面写过登录过程声明然后写入功能列表页面的测试用例

Now what i have do is below I have write the login process in the before each statement and then write the test case for the features listing page

可以让我知道我如何获得 current_user

Can you please let me know that how i can get the current_user ?

FYI,我已经使用devise宝石,并与Rspec集成测试用例。

FYI, I have used devise gem and working on integration test case with Rspec

这里是我的规范文件
这里是我的 food_catego ries_spec.rb

推荐答案

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

Update: you confuse functional and integration tests. Integration test doesn't use get, because there's no controller action to test, instead you must use visit (some url). Then you have to examine content of a page, not response code (latter is for functional tests). It may look like:

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

如果你需要功能 test,这里有一个例子:

In case you'll need functional test, here's an example:

# 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

这篇关于为什么在使用Rspec和Capybara编写测试用例时无法获取current_user的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆