【发布时间】:2016-11-23 20:06:55
【问题描述】:
我在应用程序中有一个控制器:
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
现在我要测试 show 方法的逻辑,应该写一些期望,比如:
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)>'
还是有问题
【问题讨论】:
-
你可以在你的规范中设置它,或者在
before each块中设置它,比如session[:cart_id] = 1111
标签: ruby-on-rails rspec shoulda