1
votes

I am using Rspec, Capybara and Devise. I need to be able to sign in.

My test:

describe "POST #create" do
  context "with valid params" do
    it "creates a new Poll" do
      @user = FactoryGirl.create(:user) 
      visit new_user_session_path

      fill_in "user_email", :with => @user.email
      fill_in "user_password", :with => "qwerty"
      click_button "commitSignIn"    

      visit '/'
      expect(page).to have_selector('.signin_username')      # OK

      binding.pry      
    end
  end
end

In the Pry console, I tried to output current_user:

[1] pry(#<RSpec::ExampleGroups::PollsController::POSTCreate::WithValidParams>)> put current_user
NameError: undefined local variable or method `current_user' for #<RSpec::ExampleGroups::PollsController::POSTCreate::WithValidParams:0x00000008011c08>
from /home/kalinin/.rvm/gems/ruby-2.0.0-p598/gems/rspec-expectations-3.3.0/lib/rspec/matchers.rb:966:in `method_missing'

For further tests I need the current_user set.

Here's how I have included the Devise::TestHelpers:

# spec/spec_helper.rb

RSpec.configure do |config|
  config.include Devise::TestHelpers, type: :controller
  config.include Devise::TestHelpers, type: :helper
  config.include ApplicationHelper
end
1

1 Answers

1
votes

I moved mine into a shared_context:

shared_context 'login' do
  def log_in_with_user(user, options={})
    email = options[:email] || user.email
    password = options[:password] || user.password
    # Do login with new, valid user account
    visit new_user_session_path
    fill_in "user_email", with: email
    fill_in "user_password", with: password, exact: true
    click_button "Log In"
  end
end

Then in your test you can do:

describe "POST #create" do
  include_context 'login'
  let(:current_user) { FactoryGirl.create(:user) }

  before do
    log_in_with_user current_user
  end

  context "with valid params" do
    it "creates a new Poll" do

      visit '/'
      expect(page).to have_selector('.signin_username')      # OK

      binding.pry      
    end
  end
end