在控制器规范中找不到数据库中的记录

时间:2015-05-29 06:00:08

标签: ruby-on-rails rspec controller

我正在尝试创建用户登录控制器

在我的控制器里面我有陈述

user = UserDetail.find_by user_name: params[ :uname ]

if user.nil?

  session[ :message ] = "User doesn't exist"
  redirect_to :back

else

  # if username and password matches then fill details
  if user.user_name == params[ :uname ] && user.password == params[ :pwd ]

    session[ :uname ] = user.user_name
    redirect_to "/expense_details/fill_expense.html"

  else

    session[ :message ] = "wrong password"
    redirect_to :back

  end

end

我在$ rails s之后在网络浏览器中尝试此操作时 "用户"变量正在填充并为username =" nilay"成功登录 密码=" nilay123"

但在我的rspec"用户"变量没有填充并保持为零

我的控制器规范有以下语句来验证登录

it "should redirect to main page with a failure notice as wrong password" do

  params = {
            :uname => 'nilay', 
            :pwd => 'abcdasgdgda'
           }

  post :match_user, params
    #expect(session[:uname]).to eq("manoj12")
    expect(session[:message]).to eq("wrong password")

end


it "should redirect to expense filling page after successful login" do

  params = {
            :uname => "nilay", 
            :pwd => "nilay123", 
           }

  post :match_user, params

  expect(session[:uname]).to eq(params[:uname])

  end
end

我收到失败消息

故障:

  1) UserLoginController should redirect to main page with a failure notice as wrong password
     Failure/Error: expect(session[:message]).to eq("wrong password")

       expected: "wrong password"
            got: "User doesn't exist"

       (compared using ==)
     # ./spec/user_login_controller_spec.rb:76:in `block (2 levels) in <top (required)>'

  2) UserLoginController should redirect to expense filling page after successful login
     Failure/Error: expect(session[:uname]).to eq(params[:uname])

       expected: "nilay"
            got: nil

       (compared using ==)
     # ./spec/user_login_controller_spec.rb:92:in `block (2 levels) in <top (required)>'

请让我知道如何实现这一目标?提前谢谢

1 个答案:

答案 0 :(得分:0)

您的测试在测试环境中运行,而服务器默认在开发环境中启动。这两个环境使用两个不同的数据库。听起来你在开发数据库中创建了名为“nilay”的用户,但没有在测试数据库中创建。

最简单的解决方案是通过在规范中包含before块来在测试数据库中创建用户,该块将在任何示例之前执行。 e.g。

RSpec.describe ... do
  before(:each) { UserDetail.create(uname: 'nilay', ... ) }

  it 'should redirect to main...' do

  it 'should redirect to expense ...' do
end