FactoryGirl.define do
factory :card do
card_no '6217920016000864'
factory :invalid_card do
card_no nil
end
end
end
card_controller_spec.rb
describe CardsController do
describe 'GET #index' do
it 'assigns card' do
card = create(:card)
get :index
expect(assigns(:card)).to eq([card])
end
it 'show index' do
expect(response).to render_template("index")
end
end
end
cards_controller.rb
class CardsController < ApplicationController
def index
if current_user.login_name=="admin"
#admin
@cardlist = set_paginate Card
else
#普通管理员
@restaurant_ids = Restaurant.where('parent_id = ? or id = ?', current_user.restaurant.id, current_user.restaurant.id).collect { |r| r.id }
@cardlist = set_paginate Card.where('restaurant_id in (?) ', @restaurant_ids)
end
end
end
有两个错误,例如expecting <"index"> but rendering with <"">
和expect(assigns(:card)).to eq([card]) got nil
。
帮助我谢谢!
答案 0 :(得分:2)
第一次测试用于数据控制器为视图提供的内容。在控制器上查看,您应该检查assigns(:cartdlist)
我认为。并使用match_array
而不是eq
。
第二次测试不会呈现任何内容,因为它不会去任何地方(您的get
仅适用于第一个it
块)。所以试试这个:
describe CardsController do
describe 'GET #index' do
before do
card = create(:card)
get :index
end
it 'assigns card' do
expect(assigns(:cardlist)).to match_array([card])
end
it 'show index' do
expect(response).to render_template("index")
end
end
end
在你的情况下可能不是问题,因为你得到了不同的错误,但允许你的spec_helper.rb文件应包含的期望语法:
RSpec.configure do |config|
# most omitted ...
config.expect_with :rspec do |c|
c.syntax = :expect
end
end
或
c.syntax = [:should, :expect]
答案 1 :(得分:1)
此
expect(assigns(:card)).to eq([card]) got nil
因为我认为您将数据分配给cards
(更新问题后:cardlist
)
此
expecting <"index"> but rendering with <"">
因为你没有在测试中调用get :index