lam*_*tor 4 rspec ruby-on-rails ruby-on-rails-3
我有一个简单的测试,几乎是脚手架产生的,虽然我无法弄清楚为什么它不起作用.情况如下:
我有一个AttachmentsController:
# POST /attachments
# POST /attachments.xml
def create
@attachment = Attachment.new(params[:attachment])
@attachment.idea_id = params[:idea_id]
respond_to do |format|
if @attachment.save
format.html { redirect_to(idea_path(params[:idea_id]), :notice => 'Attachment was successfully created.') }
format.xml { render :xml => @attachment, :status => :created, :location => @attachment }
else
format.html { render :action => "new" }
format.xml { render :xml => @attachment.errors, :status => :unprocessable_entity }
end
end
end
end
Run Code Online (Sandbox Code Playgroud)
一个规格:
describe AttachmentsController do
def mock_attachment(stubs={})
@mock_attachment ||= mock_model(Attachment, stubs).as_null_object
end
describe "POST create" do
describe "with valid params" do
it "assigns a newly created attachment as @attachment" do
Attachment.stub(:new).with({'these' => 'params'}) { mock_attachment(:save => true) }
post :create,:attachment => {'these' => 'params'}
assigns(:attachment).should be(mock_attachment)
end
Run Code Online (Sandbox Code Playgroud)
但是这个(以及本规范中的所有其他测试)都失败了
expected #<Attachment:33902000> => #<Attachment:0x2054db0 @name="Attachment_1001">
got #<NilClass:4> => nil
Run Code Online (Sandbox Code Playgroud)
因为我无法弄清楚的原因,没有调用AttachmentsController #create.
路线在那里:
POST /attachments(.:format) {:action=>"create", :controller=>"attachments"}
Run Code Online (Sandbox Code Playgroud)
这就是日志所说的:
Processing by AttachmentsController#create as HTML
Parameters: {"attachment"=>{"these"=>"params"}}
Rendered text template (0.0ms)
Completed 302 Found in 52ms (Views: 23.1ms | ActiveRecord: 0.0ms)
Run Code Online (Sandbox Code Playgroud)
我还应该注意到,我可以调用创建代码(和它的伟大工程),通过网站本身..它只是被失败的测试.
那么什么会导致post()或get()不调用这样的控制器?
您可以尝试 should_receive 并将其放入 before 块中,因为这是更好的做法:
describe AttachmentsController do
describe "POST create" do
let(:attachment) { mock_attachment(:save => save_result) }
subject { post :create, :attachment => params }
before do
Attachment.should_receive(:new).and_return(attachment)
end
describe "with valid params" do
let(:attachment_params) { {'these' => 'params'} }
let(:save_result) { true }
it "assigns a newly created attachment as @attachment" do
assigns(:attachment).should be(mock_attachment)
end
end
end
end
Run Code Online (Sandbox Code Playgroud)