当我有用户尝试接受/关注课程时,我收到了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
答案 0 :(得分:0)
it { should ... }
是简写it { subject.should ... }
,但您没有设置@user
而不是subject
。因此RSpec将创建一个隐式subject
,它只是User.new
。
您可以通过设置明确的subject
来修复测试,其设置与设置@user
的方式非常相似:
describe "taking course" do
let(:course) {FactoryGirl.create(:course)}
subject { User.create(@attr) }
before do
subject.take_course!(course)
end
it { should be_taking_course(course) }
end
如果你不想这样做,那么让你的断言更明确:
it { @user.should be_taking_course(course) }