我有两种模式:
# app/models/team.rb
class Team < ActiveRecord::Base
belongs_to :user
validates_presence_of :user
end
和
TeamsController
我正在尝试使用Rspec和factory_girl_rails来测试我的FactoryGirl.define do
factory :user do
first_name "John"
last_name "Doe"
email {|n| "email#{n}@email.com" }
mobile_phone "1235551234"
company_name "Widgets Inc."
password "password"
end
end
。
在创建新团队之前,我需要经过身份验证的用户。
我创建了一个:用户工厂:
teams_controller_spec.rb
以下是require 'rails_helper'
RSpec.describe TeamsController, type: :controller do
# This should return the minimal set of values that should be in the session
# in order to pass any filters (e.g. authentication) defined in
# TeamsController. Be sure to keep this updated too.
let(:valid_session) { {} }
describe "GET #index" do
it "assigns all teams as @teams" do
user = FactoryGirl.create(:user)
team = Team.create!(name: "New Team Name", user: user)
get :index, {}, valid_session
expect(assigns(:teams)).to eq([team])
end
end
end
的相关部分:
1) TeamsController GET #index assigns all teams as @teams
Failure/Error: get :index, {}, valid_session
NoMethodError:
undefined method `authenticate' for nil:NilClass
测试失败:
:valid_session
我不明白我需要填充{{1}}以便测试通过。我以为我必须明确地调用一个身份验证方法,但这可能不是真的。我试图测试Team控制器...而不是用户身份验证。
非常感谢任何建议。
答案 0 :(得分:2)
我在你的rails_helper中执行此操作:
module ControllerMacros
def sign_me_in
before :each do
@request.env['devise.mapping'] = Devise.mappings[:user]
@current_user = FactoryGirl.create(:user)
sign_in :user, @current_user
end
end
end
Rspec.configure do |config|
#other rspec stuff
config.include FactoryGirl::Syntax::Methods
config.extend ControllerMacros, type: :controller
config.include Devise::Test::ControllerHelpers, type: :controller
end
然后在您的控制器规范中,(如果您需要使用rails_helper),只要您想要登录而不打扰valid_session就可以sign_me_in
:
RSpec.describe TeamsController, type: :controller do
sign_me_in
#etc...
end
但是,在您的具体情况下,您想知道自己是谁,因此您可以这样做:
RSpec.describe TeamsController, type: :controller do
describe "GET #index" do
it "assigns all teams as @teams" do
user = FactoryGirl.create(:user)
team = Team.create!(name: "New Team Name", user: user)
@request.env['devise.mapping'] = Devise.mappings[:user]
sign_in :user, user
get :index
expect(assigns(:teams)).to eq([team])
end
end
end
在您的情况下可能不需要设计映射行,但不能检查您的完整应用程序。