我试图为子控制器编写一些控制器规范,在本例中为Admin :: UsersController
它有一套基本的CRUD动作。
我的users_controller_spec.rb
describe Admin::CarriersController do
before(:each) do
sign_in FactoryGirl.create(:admin)
end
it "should have a current_user" do
subject.current_user.should_not be_nil
end
describe "GET 'index'" do
it "assigns all users as @users" do
user = create(:user)
get :index
assigns(:users).should eq [user]
end
it "renders the index view" do
get :index
expect(response).to render_template :index
end
end
end
现在遇到的问题是索引操作。我的控制器工作,是一个简单的@users = User.all
复杂的事情是我的用户表是STI所以
class User < ActiveRecord::Base
end
class Client < User
end
class Seller < User
end
我的工厂
FactoryGirl.define do
factory :user do
name { Faker::Company.name }
sequence(:email) {|n| "test#{n}@test.com"}
password "password"
password_confirmation {|instance| instance.password }
type "Seller"
factory :admin do
type "Admin"
end
factory :seller do
type "Seller"
end
factory :client do
type "Client"
end
end
end
显然,eq方法不起作用,因为RSpec在我的分配(:用户)期望中匹配类名时出现问题。 我的确切错误是:
1) Admin::UsersController GET 'index' assigns all users as @users
Failure/Error: assigns(:users).should eq user
expected #<ActiveRecord::Relation [#<Client id: 1282, name: "Marks-Kozey", type: "Client"...]> to eq #<User id: 1282, name: "Marks-Kozey", type: "Client"...
我的问题是我的工厂吗?或者我测试不正确。这是我第一次测试STI,所以任何帮助都会很有意义。
答案 0 :(得分:2)
尝试将类符号传递给子工厂,例如:
factory :client, class:Client do
type "Client"
end
工厂生成的对象应该是Client
类型,而不是User
。