Why i can not get current_user while writing test

2019-05-31 15:58发布

问题:

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

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

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

Here is my spec file And here is my food_categories_spec.rb

回答1:

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'

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