Rails测试夹具用户的电子邮件显示为null

时间:2017-03-08 17:48:04

标签: ruby-on-rails unit-testing fixtures

我正在尝试测试登录系统是否正常工作。我已经为测试用户创建了一个用户夹具。

测试/装置/ users.yml里

dave:
  name: Mr Dave
  email: dave@dave.com
  password_digest: <%= User.digest('password') %>

我为登录系统创建了一个单元测试,用于测试用户登录和注销。

测试/集成/ site_layout_test.rb

require 'test_helper'

def setup
    @user = users(:dave)
end

...

  test "login with valid information followed by logout" do
    get login_path
    post login_path, params: { session: { email:    @user.email,
                                          password: 'password' } }
    assert is_logged_in?
    assert_redirected_to @user
    follow_redirect!
    assert_template 'users/show'
    assert_select "a[href=?]", login_path, count: 0
    assert_select "a[href=?]", logout_path
    assert_select "a[href=?]", user_path(@user)
    delete logout_path
    assert_not is_logged_in?
    assert_redirected_to root_url
    follow_redirect!
    assert_select "a[href=?]", login_path
    assert_select "a[href=?]", logout_path,      count: 0
    assert_select "a[href=?]", user_path(@user), count: 0
  end
end

当我尝试运行测试时,我收到一条错误消息,指出NilClass没有电子邮件方法。

Error:
SiteLayoutTest#test_login_with_valid_information_followed_by_logout:
NoMethodError: undefined method `email' for nil:NilClass
    test/integration/site_layout_test.rb:35:in `block in <class:SiteLayoutTest>'

为什么Rails没有拿起我添加到fixtures文件夹的用户?

2 个答案:

答案 0 :(得分:0)

原因是setup在测试类之外,因此无法运行。将它移到类声明中,它将顺利运行。

class SomeTest < ActionDispatch::IntegrationTest
  def setup
    @user = users(:dave)
  end

答案 1 :(得分:-1)

我认为它应该让你朝着正确的方向前进,如果你还有问题,请告诉我How to create a test user in test/fixtures/user.yml that can be used for integration test in Devise 4?