【发布时间】:2014-06-28 06:34:04
【问题描述】:
我正在为 Rspec 中的 Rails 编写我的第一个控制器测试。在测试 create 操作时,我想编写一个测试来验证在提交带有无效属性的表单时是否呈现了“新”模板。在这种情况下,这意味着一个字段是空白的。
我找到了几个我尝试逐字逐句遵循的示例。但是,当使用 Rspec 触发创建操作时,似乎 ActiveRecord 实际上会尝试创建由于验证而失败的记录。因此,在我测试重定向功能之前,我的测试就失败了。对于编写教程或 StackOverflow 答案的人来说,这似乎不是问题。
在给定无效属性的情况下,在控制器中测试创建操作的最佳方法是什么?
Rails 4.0.0、Ruby 2.0.0、Rspec 3.0.0.beta2
order_items_controller_spec
describe "POST create" do
context "with invalid attributes" do
it "re-renders the new method" do
post :create, order_item: FactoryGirl.attributes_for(:order_item, :buyer_id => nil)
expect( response ).to render_template :new
end
end
end
order_items_controller
def create
@order_item = OrderItem.new(order_item_params)
respond_to do |format|
if @order_item.save!
format.html { redirect_to cart_path(@order_item), notice: 'Your trip has been added to your cart.' }
format.json { render action: 'show', status: :created, location: @order_item }
else
format.html { redirect_to new_order_item_path, notice: 'We were unable to customize your trip.' }
format.json { render json: @order_item.errors, status: :unprocessable_entity }
end
end
end
rspec 错误信息:
OrderItemsController POST create with invalid attributes re-renders the new method
Failure/Error: post :create, order_item: FactoryGirl.attributes_for(:order_item, :buyer_id => nil)
ActiveRecord::RecordInvalid:
Validation failed: Buyer can't be blank
# ./app/controllers/order_items_controller.rb:30:in `block in create'
# ./app/controllers/order_items_controller.rb:29:in `create'
# ./spec/controllers/order_items_controller_spec.rb:43:in `block (4 levels) in <top (required)>'
提前致谢。
【问题讨论】:
标签: ruby-on-rails rspec