我有一個rspec /工廠女孩測試,我無法通過測試。Rspec工廠女孩問題
我在使用設計current_user調用當前登錄的用戶模型。
我可以加載了一個測試控制檯,輸入
u = Factory(:user)
u.company
,這將返回一個有效的公司,但由於某種原因在rspec的調用current_user.company將返回零。
任何想法?
控制器
class CompaniesController < ApplicationController
before_filter :authenticate_user!
def show
@company = current_user.company
end
end
模型
class User < ActiveRecord::Base
validates_uniqueness_of :email, :case_sensitive => false
has_one :company
end
廠
Factory.define :company do |f|
f.name 'Test Company'
end
Factory.sequence(:email) do |n|
"person#{n}@example.com"
end
Factory.define :user do |f|
f.name 'Test User'
f.email {Factory.next :email}
f.password 'password'
f.company Factory(:company)
end
維護設備噸
describe CompaniesController do
before(:each) do
@user = Factory(:user)
sign_in @user
end
describe "GET show" do
before do
get :show
end
it "should find the users company" do
assigns(:company).should be_a(Company)
end
end
end
規格助手
RSpec.configure do |config|
config.before(:suite) do
DatabaseCleaner.strategy = :transaction
end
config.before(:each) do
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
config.infer_base_class_for_anonymous_controllers = false
end
測試結果
Failures:
1) CompaniesController GET show should find the users company
Failure/Error: assigns(:company).should be_a(Company)
expected nil to be a kind of Company(id: integer, name: string, user_id: integer, created_at: datetime, updated_at: datetime)
# ./spec/controllers/companies_controller_spec.rb:21:in `block (3 levels) in <top (required)>'
EDIT
我已刪除了f.company =出廠(:COMPA ny)在工廠文件中。搞得我控制器規範這個
需要「spec_helper」
describe CompaniesController do
let(:current_user) { Factory(:user) }
before(:each) do
sign_in current_user
current_user.company = Factory(:company)
current_user.save
end
describe "GET show" do
before do
get :show
end
it "should find the users company" do
current_user.should respond_to(:company)
assigns(:company).should == current_user.company
end
end
end
我不認爲你可以在前面的塊中使用let。 雖然我朝這個方向前進,但我會將我的代碼附加到我的主要帖子中 – Marklar 2012-03-28 19:44:53