标题几乎解释了这个问题。我已经将提交的JSON POST数据从开发服务器上的成功提交粘贴到测试中并且它不起作用,所以我相信问题在于我如何测试,而不是在控制器中
此外,该应用程序的测试套件已经非常成熟,因此我无法切换到RSpec。
这是失败的消息:
1) Failure:
LessonsControllerTest#test_create [/test/controllers/lessons_controller_test.rb:24]:
"Lesson.count" didn't change by 1.
Expected: 1
Actual: 0
这是我的测试
def setup
@user1 = users(:michael).id
@user2 = users(:john).id
@date1 = Date.parse('30-8-2015')
@date2 = Date.parse('31-8-2015')
@school1 = schools(:hhs).id
@school2 = schools(:harper).id
end
test "create" do
# Invalid submission
assert_no_difference ['Goal.count', 'Lesson.count'] do
post :create, lesson: { date: @date1,
school_id: @school1,
user_id: @user1,
goals_attributes: {'0' => { text: '',
user_id: @user1 }}}
end
# Valid submission
assert_difference ['Goal.count', 'Lesson.count'], 1 do
post :create, lesson: { date: @date1,
school_id: @school1,
user_id: @user1,
goals_attributes: {'0' => { text: 'test',
user_id: @user1 }}}
end
这是我的控制器,虽然我确定错误在其他地方
def create
find_or_initialize_lesson
if @lesson.save
flash[:success] = "Response logged"
redirect_to @lesson
else
@user = current_user
@school_options = School.all.map { |s| [s.name, s.id] }
render 'new'
end
end
private
# strong params
def lesson_params
params.require(:lesson).permit(:school_id, :date,
goals_attributes: [:id, :user_id,
:text, :lesson_id])
end
# Finds a lesson with the same date and school, or creates the lesson
def find_or_initialize_lesson
@lesson = Lesson.find_or_initialize_by(
date: lesson_params[:date],
school_id: lesson_params[:school_id]
)
goal = Goal.new(lesson_params[:goals_attributes]['0'])
@lesson.goals << goal
end
lesson.rb:
class Lesson < ActiveRecord::Base
belongs_to :school
has_many :users, through: :goals
has_many :goals, dependent: :destroy
validates_presence_of :date, :school_id
accepts_nested_attributes_for :goals
end
goal.rb
class Goal < ActiveRecord::Base
belongs_to :lesson
belongs_to :user
validates_presence_of :text
end
schools.yml
hhs:
name: Hillsborough High School
harper:
name: Harper High School
users.yml里
michael:
id: 1
name: Michael Example
email: test@example.com
admin: false
activated: true
activated_at: <%= Time.zone.now %>
password_digest: <%= User.digest('password') %>
john:
id: 3
name: John Example
email: john@example.com
admin: false
activated: true
activated_at: <%= Time.zone.now %>
password_digest: <%= User.digest('password') %>