未定义的局部变量或方法`user'for#<class:0x00000007dc99c8>(NameError)</class:0x00000007dc99c8>

时间:2014-10-17 13:05:34

标签: ruby-on-rails rspec

我正在编写测试以检查登录是否为用户创建了remember_digest。 这是数据库的模式:

ActiveRecord::Schema.define(version: 20141015163624) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "users", force: true do |t|
    t.string   "name"
    t.string   "email"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "password_digest"
    t.string   "remember_digest"
  end

  add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree

end

这是测试文件:

require 'rails_helper'

RSpec.describe "UserPages", :type => :request do  

  describe "signup" do

    before { visit signup_path }

    describe "with valid information" do
      before do
        fill_in "name",         with: "Example User"
        fill_in "email",        with: "user@example.com"
        fill_in "password",     with: "foobar"
        fill_in "password confirmation", with: "foobar"
      end

      describe "after saving the user" do
        before { click_button submit }
        let(:user) { User.find_by(email: 'user@example.com') }

        describe "remember digest" do
          expect(user.remember_digest).not_to be_blank
        end
      end
    end
  end
end

但是我在运行rspec时遇到了这个错误:

`block (5 levels) in <top (required)>': undefined local variable or method `user' for #<Class:0x00000007dc99c8> (NameError)

1 个答案:

答案 0 :(得分:0)

用户before(:each)before(:all)。看来,正在创建的对象超出了表单提交的范围。

尝试:

describe "signup" do

  before(:each) { visit signup_path }

  describe "with valid information" do

    before(:all) do
      fill_in "name",         with: "Example User"
      fill_in "email",        with: "user@example.com"
      fill_in "password",     with: "foobar"
      fill_in "password confirmation", with: "foobar"
      click_button submit 
    end

    it "has remember digest value" do
      expect(User.find_by_email('user@example.com')).not_to be_blank
    end
  end
end

如果这不起作用,可能是因为您无法访问Rspec文件中的User类。