当我让用户尝试参加/学习课程时,我收到了 rspec 错误。我相信我的方法一定有问题,因为它在 rspec 测试中返回 nil。在课程模型和用户模型之间还有一个分配模型。怎么了?
错误
1) User taking course
Failure/Error: it { should be_taking_course(course)}
expected taking_course?(#<Course id: 1, title: "Ze Finance Course 1", description: "Description for course 1", typeof: nil, created_at: "2013-06-25 21:38:24", updated_at: "2013-06-25 21:38:24">) to return true, got nil
# ./spec/models/user_spec.rb:125:in `block (3 levels) in <top (required)>'
我的用户模型
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :name, :email, :password, :password_confirmation, :remember_me
has_many :assignments, foreign_key: "user_id", dependent: :destroy
has_many :courses, through: :assignments
def taking_course?(course)
assignments.find_by_course_id(course.id)
end
def take_course!(course)
assignments.create!(course_id: course.id)
end
end
用户规格
require 'spec_helper'
describe User do
before(:each) do
@attr = {
:name => "Example User",
:email => "user@example.com",
:password => "changeme",
:password_confirmation => "changeme"
}
end
describe "taking course" do
let(:course) {FactoryGirl.create(:course)}
before do
@user = User.new(@attr)
@user.save
@user.take_course!(course)
end
it { should be_taking_course(course)} //this is the problem test
end
end