我正在开发一个项目来学习如何在轨道上使用带有ruby的rspec。
所以我编写了一个规范来测试我的应用是否在用户已经允许接收电子邮件时通过电子邮件发送新评论,如果用户未授权则不会发送电子邮件。
###COMMENT SPEC###
require 'rails_helper'
describe Comment do
include TestFactories
describe "after_create" do
before do
@post = associated_post
@user = authenticated_user
@comment = Comment.new(body: 'My comment', post: @post, user_id: 1000)
end
context "with user's permission" do
it "sends an email to users who have favorited the post" do
@user.favorites.where(post: @post).create
allow( FavoriteMailer )
.to receive(:new_comment)
.with(@user, @post, @comment)
.and_return( double(deliver: true) )
@comment.save ### Test fails if this changes to @comment.save!
end
it "does not send emails to users who haven't" do
expect( FavoriteMailer )
.not_to receive(:new_comment)
@comment.save ### Test fails if this changes to @comment.save!
end
end
context "without permission" do
before { @user.update_attribute(:email_favorites, false) }
it "does not send emails, even to users who have favorited" do
@user.favorites.where(post: @post).create
expect( FavoriteMailer )
.not_to receive(:new_comment)
@comment.save ### Test fails if this changes to @comment.save!
end
end
end
end
这是我的测试工厂
module TestFactories
def associated_post(options={})
post_options = {
title: 'Post title',
body: 'Post bodies must be pretty long.',
topic: Topic.create(name: 'Topic name'),
user: authenticated_user
}.merge(options)
Post.create(post_options)
end
def authenticated_user(options={})
user_options = {email: "email#{rand}@fake.com", password: 'password'}.merge(options)
user = User.new(user_options)
user.skip_confirmation!
user.save
user
end
end
现在如果我将@ comment.save更改为@ comment.save!对于规范中的测试,测试失败,我收到以下错误:
Comment after_create without permission does not send emails, even to users who have favorited
Failure/Error: @comment.save!
ActiveRecord::RecordInvalid:
Validation failed: User can't be blank
我的工厂存在缺陷还是这个测试存在缺陷? 我对真正的错误感到困惑。
谢谢!