ruby-on-rails – RSpec测试不调用控制器
发布时间:2020-12-17 03:59:12 所属栏目:百科 来源:网络整理
导读:我有一个简单的测试,几乎是脚手架产生的,虽然我无法弄清楚为什么它不起作用.情况如下: 我有一个AttachmentsController: # POST /attachments # POST /attachments.xml def create @attachment = Attachment.new(params[:attachment]) @attachment.idea_id
我有一个简单的测试,几乎是脚手架产生的,虽然我无法弄清楚为什么它不起作用.情况如下:
我有一个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 一个规格: 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 但是这个(以及本规范中的所有其他测试)都失败了 expected #<Attachment:33902000> => #<Attachment:0x2054db0 @name="Attachment_1001"> got #<NilClass:4> => nil 因为我无法弄清楚的原因,没有调用AttachmentsController #create. 路线在那里: POST /attachments(.:format) {:action=>"create",:controller=>"attachments"} 这就是日志所说的: 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) 我还应该注意,我可以通过网站本身调用创建代码(并且它工作得很好).这只是失败的测试. 那么什么会导致post()或get()不调用这样的控制器? 解决方法
您可以尝试使用should_receive并将其放入块之前,因为这是一种更好的做法:
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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |