我有以下RSpec的测试:如何将参数传递给rspec控制器测试?
def valid_attributes
{ "product_id" => "1" }
end
describe "POST create" do
describe "with valid params" do
it "creates a new LineItem" do
expect {
post :create, {:line_item => valid_attributes}, valid_session #my valid_session is blank
}.to change(LineItem, :count).by(1)
end
哪些失败,此错误:
1) LineItemsController POST create with valid params redirects to the created line_item
Failure/Error: post :create, {:line_item => valid_attributes}, valid_session
ActiveRecord::RecordNotFound:
Couldn't find Product without an ID
# ./app/controllers/line_items_controller.rb:44:in `create'
# ./spec/controllers/line_items_controller_spec.rb:87:in `block (4 levels) in <top (required)>'
这是我的控制器的创建操作:
def create
@cart = current_cart
product = Product.find(params[:product_id])
@line_item = @cart.line_items.build(:product => product)
respond_to do |format|
if @line_item.save
format.html { redirect_to @line_item.cart, notice: 'Line item was successfully created.' }
format.json { render json: @line_item.cart, status: :created, location: @line_item }
else
format.html { render action: "new" }
format.json { render json: @line_item.errors, status: :unprocessable_entity }
end
end
end
正如你看到的,我的行动预计请求的params
对象中的product_id。 我应该如何将这个product_id加入我的rspec测试?
我试图把这个before
声明:
before(:each) do
ApplicationController.any_instance.stub(:product).and_return(@product = mock('product'))
end
。 。 。但它没有改变。我在某处丢失了一些rspec概念。
当我做出改变,我的错误更改:'难道找不到ID产品= 1'这是因为没有代表产品的固定装置 - 我应该如何解决这个问题?我觉得将物体剔除会更好,但是创建一个夹具是更合适的解决方案? – Ecnalyr
我使用RSpec的mock_model,请检查:http://fr.ivolo.us/posts/rspec-tutorial-part-4-mocking –
我不确定我实际上应该在哪里存根产品,以便它显示在params对象的上下文中。我已经在'expect {之前尝试过了。 。 。 }'块,并在'之前'块 - 但我不知道是否我的语法是问题或者如果我有上下文错误。 (我反复留下错误:'找不到产品id = 1') – Ecnalyr