我对测试比较陌生,对Rails 4和rSpec非常陌生。我正在尝试测试一个控制器,该控制器使用Devise进行身份验证,结果我被卡住了。我能找到的所有例子都是针对Rails 3的。
我使用Rails 4.0.3、Design3.2.3、rSpec 2.14.1和FactoryGirl 4.4.0。
class LessonPlansController < ApplicationController
before_action :authenticate_user!
# GET /lesson_plans
def index
@lesson_plans = current_user.lesson_plans.to_a
end
.
.
.
private
# Use callbacks to share common setup or constraints between actions.
def set_lesson_plan
@lesson_plan = LessonPlan.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def lesson_plan_params
params[:lesson_plan]
end
def lesson_plan_params
params.require(:lesson_plan).permit(:title, :synopsis)
end
end以下是我的工厂定义:(也许我不需要在user_id工厂中定义lesson_plan?)
FactoryGirl.define do
factory :user do
sequence( :username ) { |n| "user#{n}" }
sequence( :email ) { |n| "foo#{n}@example.com" }
password 'foobarbaz'
password_confirmation 'foobarbaz'
created_at Time.now
updated_at Time.now
end
end
FactoryGirl.define do
factory :lesson_plan do
user_id 1
title "The French Revolution"
synopsis "Background and events leading up to the French Revolution"
end
end测试部分是我被卡住的地方。
describe LessonPlansController do
let(:valid_attributes) { { } }
let(:valid_session) { {} }
# describe "GET index" do
it "assigns all lesson_plans as @lesson_plans" do
user=FactoryGirl.create(:user)
sign_in user
lesson_plan = LessonPlan.create! valid_attributes
get :index, {}, valid_session
assigns(:lesson_plans).should eq([lesson_plan])
end
end我不知道在valid_attributes和valid_session中放什么(或者我是否需要它们)。测试将深入到在用户中签名,但在创建lesson_plan时将失败。诚然,这是rSpec的默认/生成测试,但我不确定如何继续。
我见过的示例使用了一个前置块来设置用户。我还没有在Devise页面上找到任何东西,包括如何为需要用户登录的控制器编写基本的rSpec测试。任何指点都将不胜感激!
发布于 2014-03-13 00:41:38
"I'm not sure what to put in valid_attributes and valid_session (or if I even need them)."
那要看你在测试什么..。假设您正在测试验证&希望确保如果x列设置为null,则不创建记录.然后,您可以尝试使用无效属性(例如column: nil)专门创建一个记录,并期望结果不返回true;也许您希望确保它是用有效属性创建的。
顺便说一下,使用`attributes_for(:factory_name),因为您使用的是FactoryGirl。不,您不一定需要在您的课程计划工厂中指定用户的id;除非您总是希望它引用用户1,您可以简单地引用没有值的用户。请查看http://everydayrails.com/2012/03/12/testing-series-intro.html,特别是第3-5部分,以了解如何使用RSPec进行测试。当我开始的时候,我发现这是一个很容易遵循的指南。
https://stackoverflow.com/questions/22366566
复制相似问题