简体   繁体   中英

Assigns usage in Rspec

I'd like to ask why i'm always getting nil value when running rspec controller test ? I already read in this site and most of answers because plurals word using inside assigns but in my case thats not working and i still got the same value This is my Controller

  class ContactsController < ApplicationController
  load_and_authorize_resource
  before_action :find_contact, only: [:show,:edit,:update,:destroy]

  def index
    authorize! :index, Contact
    @contact = Contact.accessible_by(current_ability)
    # @contact = Contact.all
  end

  def show
  end

  def new
    @contact = Contact.new
  end

  def edit
  end

  def create
    @contact = current_user.contact.new(contact_params)

    if @contact.save
      redirect_to @contact
    else
      render 'new'
    end

  end

  def update
    # @contact = Contact.find(params[:id])
    if @contact.update(contact_params)
      redirect_to @contact
    else
      render 'edit'
    end

  end

  def destroy
    @contact.destroy

    redirect_to contacts_path
  end

  private

  def contact_params
    params.require(:contact).permit(:firstname,
                                    :lastname,
                                    :alamat,
                                    details_attributes: [:id, :number, :_destroy])
  end

  def find_contact
    @contact = Contact.find(params[:id])
  end
end

And this is my simple controller test

require 'rails_helper'

RSpec.describe ContactsController do

  describe "Contact"  do 

    it "succesfully create the contact" do
      contact = FactoryGirl.create(:contact)
      get :index
      # byebug
      expect(assigns(:contacts)).to eq([contact])
    end

  end

end

Even i change assigns(:contacts) to assigns(:contact) i still got the same value. So where is that i am do wrong ? Please kindly answer this, big thanks

Even i change assigns(:contacts) to assigns(:contact) i still got the same value. So where is that i am do wrong ?

assigns and assert_template have been remove and extracted to a gem in Rails 5.

Source

You have an authorization check

authorize! :index, Contact

before the assignment to @contact .

But your test has no setup in order to grant permissions to the requesting user in any way.

It probably makes sense to have an additional test alongside the one you show in order to spot errors like this. Eg:

it "returns 200 (OK)" do
  get :index
  expect(response.response_code).to eq(200)
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM