0
測試邏輯我在的應用的控制器:使用RSpec
class CartsController < ApplicationController
def show
@cart = Cart.find(session[:cart_id])
@products = @cart.products
end
end
,我寫了一些初步的規範使用,以測試響應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
現在我要測試顯示方法的邏輯和應寫一些期望像:
it 'should be products in current cart' do
end
但我不知道如何將cart.id傳遞給會話哈希
更新!我想寫什麼將與現有的購物車相關產品實例:
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
,但得到了一個錯誤:
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)>'
東西還是走錯了
你可以在你的規範中設置它,或者在每個'之前'塊,就像'session [:cart_id] = 1111' –