为什么在用Rspec和Capybara编写测试用例时我无法获得current_user

时间:2012-04-06 04:49:22

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

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

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

1 个答案:

答案 0 :(得分:3)

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

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