Ruby on rails 3 -功能测试问题



我有测试代码如下,为什么"测试"应该得到创建"做"总是失败????

  # called before every single test
  def setup
    logger.debug '2'
    @new_user = User.create(:email                 => 'shrimpy@email.com',
                            :password              => 'secret',
                            :password_confirmation => 'secret')
    logger.debug "==========> #{@new_user.id}"
  end
  # called after every single test
  def teardown
    @new_user.delete
  end

  test "should get create" do
    logger.debug '1'
    get :create, :email => "shrimpy@email.com", :password => "secret"
    assert_response :success  # <------why it always failed here?
    assert_redirected_to user_path(@new_user)
  end

控制台输出:以3.834383秒完成。

  1) Failure:
test_should_get_create(SessionsControllerTest) [test/functional/sessions_controller_test.rb:24]:
Expected block to return true value.
1 tests, 1 assertions, 1 failures, 0 errors, 0 skips
test.log:
    2
      SQL (2.0ms)  SELECT 1 FROM "users" WHERE ("users"."email" = 'shrimpy@email.com') LIMIT 1
      SQL (0.0ms)   SELECT name
     FROM sqlite_master
     WHERE type = 'table' AND NOT name = 'sqlite_sequence'
      AREL (6.0ms)  INSERT INTO "users" ("email", "hashed_password", "salt", "created_at", "updated_at") VALUES ('shrimpy@email.com', 'b4e991c44d9738effa3
    98e97d7ed1e6ccad19c90ce2e911344a21bf9c82f915f', '258003960.04544115923816805', '2011-04-21 07:04:00.891929', '2011-04-21 07:04:00.891929')
    ==========> 980190963
    1
      Processing by SessionsController#create as HTML
      Parameters: {"email"=>"shrimpy@email.com", "password"=>"[FILTERED]"}
      User Load (0.0ms)  SELECT "users".* FROM "users" WHERE "users"."email" = 'shrimpy@email.com' LIMIT 1
    Redirected to http://test.host/users/980190963
    Completed 302 Found in 166ms
      AREL (0.0ms)  DELETE FROM "users" WHERE "users"."id" = 980190963

这是我要测试的功能:

 def create
    if user = User.authenticate(params[:email], params[:password])
        session[:user_id] = user.id
        redirect_to user_path(user), :notice => 'You have successfully login'
    else
        redirect_to login_url, :alert => "Invalid email/password combination"
    end
  end

因为响应不是成功,所以响应是重定向。

要理解这一点,需要对HTTP有一点了解,对assert_response :successredirect_to有一点了解。所有的assert_response :success是测试的HTTP响应代码,它的测试,看看它是否是一个成功的代码。当您将页面呈现回浏览器时,您将获得一个成功代码。当您重定向时,不会获得成功代码,而是获得重定向代码。

所以如果你想检查响应,你可以使用assert_response :redirect -尽管这是多余的,当你已经有了assert_redirected_to

阅读更多关于Rails测试指南

相关内容

  • 没有找到相关文章

最新更新