Ruby on rails RSpec:断言成功创建请求而不指定方法
我在Rails控制器中的Ruby on rails RSpec:断言成功创建请求而不指定方法,ruby-on-rails,rspec,rspec-rails,Ruby On Rails,Rspec,Rspec Rails,我在Rails控制器中的create方法中有以下代码: if @product.save format.html { redirect_to @product, notice: 'Product was successfully created.' } 为了测试这段代码,我在RSpec文件中有这样的期望: expect(response).to redirect_to(assigns(:product)) 使用assigns已被弃用/已移动到gem,坦率地说,我不在乎控制器中是否创建了@
create
方法中有以下代码:
if @product.save
format.html { redirect_to @product, notice: 'Product was successfully created.' }
为了测试这段代码,我在RSpec文件中有这样的期望:
expect(response).to redirect_to(assigns(:product))
使用assigns
已被弃用/已移动到gem,坦率地说,我不在乎控制器中是否创建了@product
或@my_product
。实际上,我只是想知道我是否被重定向到/products/
。有(推荐的)方法吗?这解释了为什么不推荐使用assigns
测试控制器设置的实例变量是一个坏主意。这大大超出了测试应该知道的范围。您可以测试设置了哪些cookie,返回了哪些HTTP代码,视图的外观如何,或者数据库发生了哪些变化,但是测试控制器的内部并不是一个好主意
您可以使用matcher测试响应状态代码
如果您想要呈现新的,您需要将
gem'rails controller testing'
添加到Gemfile中
读了你的评论后,我猜你的行动是这样的:
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
describe 'POST /products' do
context 'when everithing is ok' do
it 'returns the product' do
post products_url, params: { product: { description: 'lorem ipsum', title: 'lorem ipsum' } }
expect(response).to redirect_to(product_url(Product.last))
end
end
context 'when something worong' do
it 'redirect to new' do
post products_url, params: { product: { description: 'lorem ipsum' } }
expect(response).to render_template(:new)
end
end
end
你可以做这样的测试:
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
describe 'POST /products' do
context 'when everithing is ok' do
it 'returns the product' do
post products_url, params: { product: { description: 'lorem ipsum', title: 'lorem ipsum' } }
expect(response).to redirect_to(product_url(Product.last))
end
end
context 'when something worong' do
it 'redirect to new' do
post products_url, params: { product: { description: 'lorem ipsum' } }
expect(response).to render_template(:new)
end
end
end
您使用的是哪个版本的
rspec-rails
?我需要rspec-rails
而不指明任何特定的版本,并且今天进行了bundle更新
,因此它是4.0.1。这不起作用,因为重定向有一个302状态代码,而成功被定义为2xx状态代码。我发布的代码中还存在另一个问题:如果将无效数据发送到create
方法,则会呈现products/new
视图(状态代码为200),因此包含有效数据的POST请求被分类为不成功,而包含无效数据的请求被分类为成功。这需要另一种方式。谢谢,这(尤其是希望重定向到(product\u url(product.last))
)就成功了!