NameError:未定义的局部变量或方法`user'

时间:2016-04-13 12:35:31

标签: ruby-on-rails ruby-on-rails-4 rspec rspec-rails

我正在使用RoR编写应用程序,使用gem Devise进行用户身份验证。我正在尝试在他登录应用程序时测试用户行为并出现下一个错误:

User::TransactionsController when logged in when its own record GET #show assigns the requested instance as @instance
     Failure/Error: let(:transaction) { FactoryGirl.create(:transaction, user_id: user.id) }

     NameError:
       undefined local variable or method `user' for #<RSpec::ExampleGroups::UserTransactionsController::WhenLoggedIn::WhenItsOwnRecord::GETShow:0x00000004d77220>

我的测试始于:

RSpec.describe User::TransactionsController, type: :controller do
  render_views

  before { sign_in FactoryGirl.create :user }

  let(:transaction_category) { FactoryGirl.create(:transaction_category) }
  let(:transaction) { FactoryGirl.create(:transaction, user_id: user.id) }
  ......
end

我的工厂:

FactoryGirl.define do
  factory :transaction do
    date '2016-01-08'
    comment 'MyString'
    amount 1
    transaction_category

    trait :invalid do
      amount nil
    end
  end
end

我的TransactionsController看起来像:

class User::TransactionsController < ApplicationController
  before_action :authenticate_user!
  before_action :find_transaction, only: [:show, :edit, :destroy, :update]

  def new
    @transaction = current_user.transactions.build
  end

  def show
  end

  def create
    @transaction = current_user.transactions.build(transaction_params)
    if @transaction.save
      redirect_to user_transaction_url(@transaction)
    else
      render :new
    end
  end

  def index
    @transactions = current_user.transactions
  end

  def edit
  end

  def destroy
    @transaction.destroy
    redirect_to user_transactions_url
  end

  def update
    if @transaction.update(transaction_params)
      redirect_to user_transaction_url
    else
      render :edit
    end
  end

  private

  def transaction_params
    params.require(:transaction).permit(:amount, :date, :comment,
                                        :transaction_category_id)
  end

  def find_transaction
    @transaction = current_user.transactions.find(params[:id])
  end
end

谢谢!

1 个答案:

答案 0 :(得分:0)

您需要定义用户

RSpec.describe User::TransactionsController, type: :controller do


render_views
  user = FactoryGirl.create( :user )
  before { sign_in( user ) }

  let(:transaction_category) { FactoryGirl.create(:transaction_category) }
  let(:transaction) { FactoryGirl.create(:transaction, user_id: user.id) }
  ......
end