使用 rspec 测试逻辑
Test logic with 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
现在我要测试 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)>'
仍有问题
您可以在控制器测试中设置会话
it 'should be products in current cart' do
session[:cart_id] = 10
get :show
end
我在应用程序中有一个控制器:
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)>'
仍有问题
您可以在控制器测试中设置会话
it 'should be products in current cart' do
session[:cart_id] = 10
get :show
end