Rspec Capybara丢失饼干

时间:2013-11-27 13:28:49

标签: ruby-on-rails rspec capybara

我正在尝试按照本指南设置我的功能测试: https://github.com/integrallis/learn-rspec-capybara

由于指南中的示例很好,我正在尝试在我的项目中执行相同的操作。但我的测试失败了,因为cookie一直在丢失。

describe "Profile Sessions" do
  before do
    @profile= Profile.new
    @profile.assign_attributes(FactoryGirl.attributes_for(:profile))
    @profile.password = "123456"
    @profile.password_confirmation = "123456"
    @profile.verified = true
    @profile.save
  end

  before do
    visit signin_path
  end  

  context "success" do
    before do
      fill_in 'Mail', with: @profile.email, :match => :prefer_exact
      fill_in 'Password', with: "123456", :match => :prefer_exact
      click_button 'Sign In', :match => :prefer_exact
    end

    it "should be profile page" do
      current_path.should == profile_path(@profile)
    end

    it "displays a welcome message" do
      expect(page).to have_content('Signed in successfully.')
    end
  end
end

SessionsController

def create
  profile = Profile.find_by_email(params[:session][:email].downcase)
  if profile && profile.authenticate(params[:session][:password])
  if profile.verified
    sign_in profile
    redirect_to current_profile
  else
    flash[:error] = I18n.translate('signup.not_verified')
    redirect_to root_url
  end
  else
    flash.now[:error] = 'Invalid email/password combination' 
    render 'new'
  end
end

在日志文件中,我可以看到登录过程成功并将其重定向到配置文件页面。这里应用了before_filter:

def login_required
  unless signed_in?
    redirect_to signin_path, :alert => "You must first log in or sign up before accessing this page."
  end
end

SessionsHelper

def sign_in(profile)
 remember_token = Profile.new_remember_token
 cookies.permanent[:remember_token] = remember_token
 profile.update_attribute(:remember_token, Profile.encrypt(remember_token))
  self.current_profile = profile
end

def signed_in?
  !current_profile.nil?
end

def current_profile=(profile)
  @current_profile = profile
end

def current_profile
  remember_token = Profile.encrypt(cookies[:remember_token])
  @current_profile ||= Profile.find_by_remember_token(remember_token)
end

def sign_out
  self.current_profile = nil
  cookies.delete(:remember_token)
end 

重定向到个人资料页面后,remember_token cookie为nil,因此该个人资料未登录。

编辑1: 如果我在登录后进行了visit_page,则测试通过:

  context "success" do
    before do
      fill_in 'Mail', with: @profile.email, :match => :prefer_exact
      fill_in 'Password', with: "123456", :match => :prefer_exact
      click_button 'Sign In', :match => :prefer_exact
    end

    it "should be profile page" do
      visit profile_path(@profile)
      current_path.should == profile_path(@profile)
    end

    it "displays a welcome message" do
      visit profile_path(@profile)
      expect(page).to have_content('Signed in successfully.')
    end
  end

但是SessionsController重定向后会出现什么问题?

0 个答案:

没有答案