我创建了一个电影评论网站,允许登录用户添加,编辑和删除电影以及为每部电影留下评论。我还为我的联系表单实现了一个邮件,它发送一个“假电子邮件”(仅在控制台上显示)。
这是我第一次使用Ruby,所以我不确定如何测试我的控制器和联系方法。任何形式的建议将不胜感激。
contacts_controller.rb:
class ContactsController < ApplicationController
def new
@contact = Contact.new
end
def create
@contact = Contact.new(params[:contact])
@contact.request = request
if @contact.deliver
flash.now[:notice] = 'Thank you for your message. We will contact you soon!'
else
flash.now[:error] = 'Cannot send message.'
render :new
end
end
end
contact.rb:
class Contact < MailForm::Base
attribute :name, :validate => true
attribute :email, :validate => /\A([\w\.%\+\-]+)@([\w\-]+\.
attribute :message
attribute :nickname, :captcha => true
# Declare the e-mail headers. It accepts anything the mail method
# in ActionMailer accepts.
def headers
{
:subject => "My Contact Form",
:to => "your_email@example.org",
:from => %("#{name}" <#{email}>)
}
end
end
路线:
contacts GET /contacts(.:format) contacts#new
POST /contacts(.:format) contacts#create
new_contact GET /contacts/new(.:format) contacts#new
到目前为止我的测试:
require 'test_helper'
class ContactsControllerTest < ActionController::TestCase
include Devise::Test::ControllerHelpers
test "should get contact" do
get :new
assert_response :success
end
end
答案 0 :(得分:0)
您可以在此处阅读更多信息http://edgeguides.rubyonrails.org/testing.html#testing-your-mailers
require 'test_helper'
class ContactsControllerTest < ActionDispatch::IntegrationTest
test "ActionMailer is increased by 1" do
assert_difference 'ActionMailer::Base.deliveries.size', +1 do
post contacts_url, params: { name: 'jack bites', email: 'bite@jack.org', message: 'sending message', nickname: 'jackbites' }
end
end
test "Email is sent to correct address" do
post contacts_url, params: { name: 'jack bites', email: 'bite@jack.org', message: 'sending message', nickname: 'jackbites' }
invite_email = ActionMailer::Base.deliveries.last
assert_equal 'bite@jack.org', invite_email.to[0]
end
end