测试设计视图时Stub current_user

时间:2013-10-30 16:01:36

标签: ruby-on-rails rspec devise capybara

我正在使用capybara测试我的自定义设计视图,我需要一个登录用户才能测试一些视图,例如:

feature 'user/edit' do
  describe "the edit profile process", :type => :feature do
    include Devise::TestHelpers

    let!(:user){ FactoryGirl.build(:user)

    def sign_in(user)
      if user.nil?
        request.env['warden'].stub(:authenticate!).
          and_throw(:warden, {:scope => :user})
          controller.stub :current_user => nil
      else
        request.env['warden'].stub :authenticate! => user
         controller.stub :current_user => user
      end
    end

    it "update " do
      sign_in(user)
      visit '/users/edit'
      within("#edit_user") do  
         #=> something
      end
      click_on 'Update'
      page.should have_content("something")
    end
  end
end

但我收到了这个错误

Failure/Error: request.env['warden'].stub :authenticate! => user

NoMethodError: undefined method `env' for nil:NilClass

1 个答案:

答案 0 :(得分:1)

模块Devise::TestHelpers建立@request实例变量。您引用的是request,在其他可访问的范围内显然设置为nil,导致您收到错误。

有关TestHelpers的来源,请参阅https://github.com/plataformatec/devise/blob/b8ed2f31608eccb6df6d5bb2e66238d6dfc4bcfc/lib/devise/test_helpers.rb