见了鬼了。@contest明明有值,还 respond_to save,下一条里就成 NilClass 了。是我对 Ruby 的理解有误么?
# coding: utf-8
class ContestsController < ApplicationController
def create
@contest = Contest.new(params[:contest])
p '@contest supports save' if @contest.respond_to?(:save)
if @contest.save
flash[:notice] = '创建成功'
redirect_to home_path
else
flash[:error] = '创建失败'
render :action => :new
end
end
end
输出
Running: spec/controllers/contests_controller_spec.rb spec/models/contest_spec.rb
F"@contest supports save"
F*F
Pending:
ContestsController POST create redirects to add mission page
# Not yet implemented
# ./spec/controllers/contests_controller_spec.rb:16
Failures:
1) ContestsController POST create creates a contest
Failure/Error: post :create, contest: { 'name' => contest.name }
NoMethodError:
undefined method `save' for nil:NilClass
# ./app/controllers/contests_controller.rb:6:in `create'
# ./spec/controllers/contests_controller_spec.rb:9:in `block (3 levels) in <top (required)>'
补上 spec
describe ContestsController do
let(:my_contest) { FactoryGirl.create(:contest) }
before(:each) { my_contest }
describe 'POST create' do
it 'creates a contest' do
Contest.should_receive(:new).with(name: my_contest.name)
post :create, contest: { name: my_contest.name }
end
it 'saves the contest' do
Contest.stub(:new).and_return(my_contest)
my_contest.should_receive(:save)
post :create
end
it 'redirects to add mission page'
end
end