Rspec指定在添加更多代码时失败

时间:2014-11-03 17:18:23

标签: ruby-on-rails ruby rspec

控制器:如果出现以下测试失败:

 def index
    @products = Product.all
    @products.present? ? @no_products_found = "" : @no_products_found = "No Products available."
 end

失败讯息:             预期:2             得到:0

   (compared using ==)

Rspec:

it "assigns products" do
  get :index
  FactoryGirl.create(:product, name: "product 1")
  FactoryGirl.create(:product, name: "product 2")
  expect(assigns(:products).size).to eq(2)
end

如果我将操作更改为:

,则会通过
 def index
    @products = Product.all
 end

PS:铁杆新手。感谢您的投入。

2 个答案:

答案 0 :(得分:1)

这是因为您在调用index方法后创建了产品。将规格更改为:

it "assigns products" do
  FactoryGirl.create(:product, name: "product 1")
  FactoryGirl.create(:product, name: "product 2")
  # created products above and then make call to index:
  get :index
  expect(assigns(:products).size).to eq(2)
end

答案 1 :(得分:1)

在执行FactoryGirl.create之前,您需要调用get。当然,记录必须在提出请求之前存在。

it "assigns products" do
  FactoryGirl.create(:product, name: "product 1")
  FactoryGirl.create(:product, name: "product 2")
  get :index
  expect(assigns(:products).size).to eq(2)
end

虽然我个人会更明确地说明这个规范:

it "assigns products" do
  get :index
    products = [
      FactoryGirl.create(:product, name: "product 1"),
      FactoryGirl.create(:product, name: "product 2")
    ]
    expect(assigns(:products)).to eq(products)
  end
end

然后您的控制器操作还有另一个问题。应谨慎使用三元条件运算符,在这种情况下,我强烈建议不要使用它,因为它会妨碍可读性。这一行:

@products.present? ? @no_products_found = "" : @no_products_found = "No Products available."

应该写成

@no_products_found = @products.present? ? "" : "No Products available."

甚至

@no_products_found = if @products.present?
                       ""
                     else
                       "No Products available."
                     end

再次,我个人不希望用这种简单的视图逻辑搞乱我的控制器动作。可能它只在一个地方使用,所以我的解决方案完全驻留在视图层中:

<% if @products.present? %>
  <% @products.each do |product| %>
    <!-- Render products -->
  <% end %>
<% else %>
  No products available.
<% end %>