2012-12-04 96 views
0

我有以下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概念。

回答

0

我最终通过使用夹具来解决我的问题,而不是像另一个答案中建议的那样尝试模拟解决方案。

原因是控制器执行查询从数据库中获取信息:product = Product.find(params[:product_id])我发现基于夹具的解决方案比使用模拟更快地解决我的问题,我无法弄清楚如何很快存根查询(固定装置也与控制器上的另一个测试有助于所以它最终反正帮助

供参考:

我引用我的灯具用这条线向测试的顶部:fixtures :products

我将测试更改为:

describe "POST create" do 
    describe "with valid params" do 
    it "creates a new LineItem" do 
     expect { 
      post :create, :product_id => products(:one).id 
     }.to change(LineItem, :count).by(1) 
    end 

这里是我的固定文件,products.yml:

one: 
    name: FirstProduct 
    price: 1.23 

two: 
    name: SecondProduct 
    price: 4.56 
0

尝试这样的:

describe "POST create" do 
    describe "with valid params" do 
     it "creates a new LineItem" do 
     expect { 
      post :create, :product_id => 1 
     }.to change(LineItem, :count).by(1) 
     end 

希望它能帮助。

+0

当我做出改变,我的错误更改:'难道找不到ID产品= 1'这是因为没有代表产品的固定装置 - 我应该如何解决这个问题?我觉得将物体剔除会更好,但是创建一个夹具是更合适的解决方案? – Ecnalyr

+0

我使用RSpec的mock_model,请检查:http://fr.ivolo.us/posts/rspec-tutorial-part-4-mocking –

+0

我不确定我实际上应该在哪里存根产品,以便它显示在params对象的上下文中。我已经在'expect {之前尝试过了。 。 。 }'块,并在'之前'块 - 但我不知道是否我的语法是问题或者如果我有上下文错误。 (我反复留下错误:'找不到产品id = 1') – Ecnalyr

相关问题