考虑到以下各点:
describe Participation do
describe "invitation by email", :focus do
let(:participation) { build :participation } # Factory
let(:email) { participation.email }
it "should send an invitation" do
# This one is failing
binding.pry # The code below is executed here
participation.should_receive(:invite_user!)
participation.save!
end
context "when user already exists" do
let!(:existing) { create :user, :email => email }
it "should not send an invitation" do
participation.should_not_receive(:invite_user!)
participation.save!
end
end
end
end
我似乎无法通过执行:
class Participation < ActiveRecord::Base
attr_accessor :email
belongs_to :user
validates :email, :email => true, :on => :create, :if => :using_email?
before_validation :set_user_by_email, :if => :using_email?, :on => :create
before_create :mark_for_invitation, :unless => :user_exists?
after_create :invite_user!, :if => :marked_for_invitation?
def using_email?
email.present?
end
def user_exists?
user.present? and user.persisted?
end
def set_user_by_email
self.user = User.find_by_email(email)
self.user ||= User.new(email: email).tap do |u|
u.status = :invited
end
end
def mark_for_invitation
@invite_user = true
true # make sure not cancelling the callback chain
end
def marked_for_invitation?
!!@invite_user
end
def invite_user!
# TODO: Send the invitation email or something
end
end
我确实看不到我做的错误。 这里是失败的光谱产生的“con”产出:
# Check the before_validation callback options:
participation.user # nil
participation.valid? # true
participation.user # User{id: nil}
# Check the before_create callback options:
participation.user_exists? # false
participation.mark_for_invitation # true
# Check the after_create callback options:
participation.marked_for_invitation? # true
# After all this I expect the "invite_user!" to be called:
participation.stub(:invite_user!) { puts "Doesn t get called :(" }
participation.save! # => true, Nothing is printed, which is consistent with the spec
participation.user_id # => 11, so the user has been saved
您可以发现<代码>的原因。 用户标准!