2016-06-15 61 views
0

我有這樣的RSpec代碼:不能滿足RSpec的

let(:valid_attributes) { 
    {name: "Sample Product"} 
    } 

    describe "#index" do 
    it "should give a collection of products" do 
     product = Product.create! valid_attributes 
     get :index, :format => :json 
     expect(response.status).to eq(200) 
     expect(response).to render_template("api/products/index") 
     expect(assigns(:products)).to eq([product]) 
    end 
    end 

而且它的控制器:

def index 
    @products = Product.all 
end 

但控制器代碼仍然不滿足規範。這裏有什麼問題。

這裏是失敗消息:

Failures:

1) Api::ProductsController#index should give a collection of products Failure/Error: expect(assigns(:products)).to eq([product])

expected: [#<Product id: 3, name: "Sample Product", created_at: "2016-06-15 05:10:50", updated_at: "2016-06-15 05:10:50">] 
     got: nil 

    (compared using ==) 
# ./spec/controllers/api/products_controller_spec.rb:53:in `block (3 levels) in <top (required)>' 

Finished in 0.05106 seconds (files took 1.89 seconds to load) 1 example, 1 failure

回答

0

您有:

get :index, :format => :json 

我想你應該有:

get :index, :format => :html 

默認情況下,軌道返回HTML,你沒在您的index操作中未指定。該實例變量被設置

  • products應該在數據庫(使用let!(與爆炸)它)創建

  • +0

    我在我的控制器中指定我想要將其呈現爲json。而且我認爲由於這一行代碼「期待(分配(:產品))」到「eq([產品])」,我得到了這個失敗。因爲當我評論它時,它通過了規範。但我需要這條線來測試我爲那個「對象」賦值。 –

    0
    • assign檢查,則:
    在你的控制器

    def index 
        @products = Product.all # `@products` should be present 
    end 
    

    in rspec:

    let(:valid_attributes) {{ name: 'Sample Product' }} 
    let!(:product) { Product.create!(valid_attributes) } # use `!` here 
    
    describe "#index" do 
        before { get :index, format :json } 
    
        it 'should give a collection of products' do 
        expect(assigns(:products)).to eq([product]) 
        end 
    end