的Rails 3.2.6Rspec的控制器測試失敗時零
我已經設置了聯繫控制器和形式這篇文章的建議: 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
The 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
我已經通過let
驗證了message
變量不是零,所以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
方法。但我現在確定它爲什麼初始化爲零。當我在開發環境中測試表單時,它似乎工作正常。謝謝你的幫助。
您似乎錯過了'it'塊中的'end'。 – Finbarr 2012-08-16 22:45:47
當我將代碼粘貼到現在已更正的StackOverflow中時發生錯字。 – 2012-08-16 22:57:01
我建議調試params [:message]的值 – Finbarr 2012-08-16 22:59:37