I'm working through the book Agile Web Development with Rails 6, but instead of Minitest and fixtures I use RSpec and FactoryBot.
I have two request tests that fail for the products
controller, but I don't understand why. Here's the code:
Tests
describe ProductsController, type: :request do
let(:valid_product) { build(:product) }
let(:invalid_product) { { 'foo' => 'bar' } }
before do
run_request
end
describe 'POST /create' do
context 'POST data is valid' do
let(:run_request) { post '/products', :params => { 'product' => valid_product.as_json } }
it 'creates a product' do
expect(response).to have_http_status(:created)
end
end
context 'POST data is invalid' do
let(:run_request) { post '/products', :params => { 'product' => invalid_product } }
it 'shows validations errors' do
expect(response).to have_http_status(:unprocessable_entity)
end
end
end
end
Model
class Product < ApplicationRecord
validates :title, :description, :image_url, presence: true
validates :title, uniqueness: true
validates :image_url, allow_blank: true, format: {
with: %r{\.(gif|jpg|png)\z}i,
message: 'must be a URL for GIF, JPG or PNG image.'
}
validates :price, numericality: { greater_than_or_equal_to: 0.01 }
end
create method
def create
@product = Product.new(product_params)
respond_to do |format|
if @product.save
format.html { redirect_to @product, notice: 'Product was successfully created.' }
format.json { render :show, status: :created, location: @product }
else
format.html { render :new }
format.json { render json: @product.errors, status: :unprocessable_entity }
end
end
end
I expect the valid and invalid requests to return a 201 and 422 status, respectively. Instead, I get 302 and 200. What's the problem?