Rails:在ActionController :: TestCase和ActionDispatch :: IntegrationTest中分配哈希

时间:2015-09-27 06:46:59

标签: ruby-on-rails

Ruby On Rails教程,Listing 10.31 Listing 10.31: Adding account activation to the user signup test.

我在这一行获得nil而不是有效用户:       user =分配(:用户)

代码在这里:

./测试/集成/ users_signup_test.rb

....
class UsersSignupTest < ActionDispatch::IntegrationTest
  test "valid signup information" do    
    assert_difference 'User.count', 1 do
    post_via_redirect users_path, user: { name:  "testA",
                                        email: "testA@valid.com",
                                        password:               "foobar",
                                        password_confirmation:  "foobar" }
    end
    assert_equal 1, ActionMailer::Base.deliveries.size
    debugger
    user = assigns(:user) 
    ....

./应用程序/控制器/ users_controller.rb

def create
  @user = User.new(user_params)   
  if @user.save
    UserMailer.account_activation(@user).deliver_now
    flash[:info] = "Please check your email to activate your account."
    redirect_to root_url  
  else
    render 'new'
  end
end

dubug信息显示分配哈希中没有:user

Run options: --seed 10699

# Running:

..............
[35, 44] in /home/artreal/Codes/hello_world/test/integration/users_signup_test.rb
   35: 
   36:     assert_equal 1, ActionMailer::Base.deliveries.size
   37: 
   38:     debugger
   39: 
   => 40:     user = assigns(:user)   #assigns (a hash) lets us access instance variables in controllers 
   41: 
   42:     assert_not user.activated?
   43:     # Try to log in before activation.
   44:     log_in_as(user)
(byebug) p assigns
{"marked_for_same_origin_verification"=>true}
{"marked_for_same_origin_verification"=>true}
(byebug) 

这是错误:

1) Error:
UsersSignupTest#test_valid_signup_information:
NoMethodError: undefined method `activated?' for nil:NilClass
test/integration/users_signup_test.rb:42:in `block in <class:UsersSignupTest>'

路线似乎是正确的:

...
users    GET    /users(.:format)                        users#index
         POST   /users(.:format)                        users#create
new_user GET    /users/new(.:format)                    users#new
...

ActionController :: TestCase 的API文档(无法发布链接)在assign hash上有一个部分。 但是 ActionDispatch :: IntegrationTest 的API文档(不能发布链接)在同一个哈希上没有说什么。

在集成测试中使用assign时我错过了什么?

1 个答案:

答案 0 :(得分:0)

发现问题。

在集成测试中,我使用了以下行:

post_via_redirect users_path, user: { name:  "testA",
                                    email: "testA@valid.com",
                                    password:               "foobar",
                                    password_confirmation:  "foobar" }

相反,本教程使用简单的post函数。

post   users_path, user: { name:  "testA",
                             email: "testA@valid.com",
                             password:               "foobar",
                             password_confirmation:  "foobar" }

是否因为重定向部分删除了assign哈希值中的值?