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