2016-04-13 90 views
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 

谢谢!

+1

变量用户缺失。创建一个:let(:user){FactoryGirl.create:user}并在之前的块中使用它。 – ksarunas

+0

@Šaras,谢谢!那有效。但在我的第一个变体是不是由'之前{sign_in FactoryGirl.create:user}'定义? – verrom

+1

在'之前'块你正在创建另一个用户和变量,它不被保存在任何地方。基本上,每次执行'FactoryGirl.create:user'时,都会创建一个新的唯一用户。因此,如果您希望有一个用户将事务附加到他身上并且也以他身份登录,则需要在'let'块中创建一个用户,以便它可以用于登录和创建新事务。 @verrom – ksarunas

回答

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 
相关问题