导轨 3.2.6
我已经按照本文的建议设置了一个联系人控制器和表单:http: //matharvard.ca/posts/2011/aug/22/contact-form-in-rails-3/
我的Message
模型课:
class Message
include ActiveModel::Validations
include ActiveModel::Conversion
extend ActiveModel::Naming
attr_accessor :name, :email, :message_body
# validations are here...
def initialize(attributes = {})
attributes.each do |name, value|
send("#{name}=", value)
end
end
def persisted?
false
end
end
Contact Controller
:_
def create
@message = Message.new(params[:message])
if @message.valid?
ContactMailer.new_message(@message).deliver
redirect_to(root_path, :notice => "Message was successfully sent.")
else
render :new
end
end
我的 rspec 控制器测试:
describe "POST create" do
context "with valid information" do
let (:message) { FactoryGirl.build(:message) }
it "creates a new message" do
post :create, params: message
assigns(:message).should eq(message)
end
end
end
我已经验证了message
变量 vialet
不是 nil,所以 FactoryGirl 正在做它的工作。
测试结果:
ContactController POST create with valid information creates a new message
Failure/Error: post :create, params: message
NoMethodError:
undefined method `each' for nil:NilClass
# ./app/models/message.rb:14:in `initialize'
# ./app/controllers/contact_controller.rb:8:in `new'
# ./app/controllers/contact_controller.rb:8:in `create'
# ./spec/controllers/contact_controller_spec.rb:22:in `block (4 levels) in <top (required)>'
我知道它失败是因为Message
'initialize
方法。但我现在确定它为什么初始化 nil。当我在开发环境中测试表单时,它似乎工作正常。谢谢你的帮助。