我有这个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
但控制器代码仍然不符合规范。这里有什么问题。
以下是失败消息:
故障:
1)Api :: ProductsController #index应该给出一个集合 制品 失败/错误:期望(指定(:产品))。到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)>'
以0.05106秒结束(文件加载1.89秒)1 例如,1次失败
答案 0 :(得分:0)
你有:
get :index, :format => :json
我认为你应该:
get :index, :format => :html
默认情况下,rails会返回html,并且您未在index
操作中另行指定。
答案 1 :(得分:0)
assign
检查是否设置了实例变量products
应该在数据库中创建(使用let!
(使用bang)),然后:在您的控制器中:
def index
@products = Product.all # `@products` should be present
end
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