1
我正在使用RoR編寫應用程序,使用gem Devise進行用戶認證。我想測試用戶的行爲,當他在登入應用程式,並有下一個錯誤:NameError:未定義的局部變量或方法'用戶'
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
謝謝!
變量用戶缺失。創建一個:let(:user){FactoryGirl.create:user}並在之前的塊中使用它。 – ksarunas
@Šaras,謝謝!那有效。但在我的第一個變體是不是由'之前{sign_in FactoryGirl.create:user}'定義? – verrom
在'之前'塊你正在創建另一個用戶和變量,它不被保存在任何地方。基本上,每次執行'FactoryGirl.create:user'時,都會創建一個新的唯一用戶。因此,如果您希望有一個用戶將事務附加到他身上並且也以他身份登錄,則需要在'let'塊中創建一個用戶,以便它可以用於登錄和創建新事務。 @verrom – ksarunas