0

当我让用户尝试参加/学习课程时,我收到了 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
4

1 回答 1

0

it { should ... }是速记it { subject.should ... },但您没有设置.@user而不是subject. 所以 RSpec 将创建一个隐含subjectUser.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) }
于 2013-06-27T10:17:53.680 回答