Rails4测试中的奇怪行为

时间:2015-11-24 22:10:42

标签: unit-testing ruby-on-rails-4 activerecord rails-activerecord

在我的测试中,我希望创建多个用户并登录最后一个用户。 所以这是我的代码:

  test "add_answer to ad" do 
    user = newuser
    text = "mytext mytext mytext mytext mytext mytext mytext"
    post :savenew, cityId: City.last.id, text: text , maxPrice: "1", subscribe: false
    $stdout.puts "#{assigns(:current_user)} CURUSER"
    @ad = assigns(:ad)
    user = newuser(0, 'new2@new.com')
    post :add_answer, id: @ad.id, text: text
    $stdout.puts "#{assigns(:current_user)} CURFIRM"
    assert_equal "Ответ успешно добавлен.", flash[:success]
    user.destroy
   end

我如何创建新用户:

def newuser(rank = 2, email = 'new@new.com')
 user = User.new
 user.password = '123456'
 user.newpassword = true
 user.email = email
 user.contact = 'new_user'
 case rank
 when 0
    user.urank = URank.firm.id
 when 1
    user.urank = URank.admin.id
 when 2
    user.urank = URank.user.id
 end
 user.save
 $stdout.puts "#{user} NEW"
 this_controller = @controller
 @controller = MainController.new
 get :logout
 post :login, email: email, pass: '123456'
 @controller = this_controller
 return user
end

我的退出:

if cookies[:id]
  Rails.cache.delete(cookies.signed[:id][0])
  cookies.delete(:id)
end
@current_user = nil

(没有缓存测试)

因此,当我创建新用户时,我可以看到: enter image description here

正如您所看到的,第一个用户只是另一个用户而第二个==第一个用户。那里发生了什么,我该如何解决这个问题? 谢谢!

1 个答案:

答案 0 :(得分:0)

我不知道为什么,但问题是

@current_user ||= User.auth_with_salt(*cookiesId)

在测试中只做

@current_user = User.auth_with_salt(*cookiesId)