a_zatula
a_zatula

Reputation: 458

Test logic with rspec

I have a controller in application:

class CartsController < ApplicationController
  def show
    @cart = Cart.find(session[:cart_id])
    @products = @cart.products
  end
end

and i wrote some initial spec to test response using rspec

RSpec.describe CartsController, type: :controller do                       
  describe 'GET #show' do
    before do
      get :show
    end
    it { expect(response.status).to eq(200) }
    it { expect(response.headers["Content-Type"]).to eql("text/html; charset=utf-8")}
    it { is_expected.to render_template :show }
  end
end

Now I am going to test show method logic and should write some expectation like:

  it 'should be products in current cart' do 
  end

but I have no idea how to pass cart.id to the session hash

Update! I am trying to write product instances what will be associated with current cart:

    let(:products_list){FactoryGirl.build_list(:product, cart_id: session[:cart_id])}
    let(:cart){FactoryGirl.build(:cart)}
    ...
    it 'should be products in current cart' do
      session[:cart_id] = cart.id
      expect(assigns(:products)).to eq([products_list])
    end   

but got an error:

    CartsController GET #show should be products in current cart
 Failure/Error: let(:cart){FactoryGirl.build(:cart)}

 ArgumentError:
   Trait not registered: products
 # ./spec/controllers/carts_controller_spec.rb:6:in `block (3 levels) in <top (required)>'
 # ./spec/controllers/carts_controller_spec.rb:15:in `block (3 levels) in <top (required)>'      

Something still going wrong

Upvotes: 0

Views: 439

Answers (1)

usha
usha

Reputation: 29349

you can set the session in your controller test

it 'should be products in current cart' do 
   session[:cart_id] = 10
   get :show
end

Upvotes: 1

Related Questions