我是 Rails 的新手,我现在正在尝试使用 stubbs 和 mocks 测试我的控制器代码。我尝试在代码上使用模拟,但我不能正确地做到这一点。请帮助我解决重构的正确代码。请帮助我解释您编写的代码。
require 'rails_helper'
RSpec.describe ArticlesController, type: :controller do
let(:article) { create :article}
let(:art_params) { attributes_for(:article) }
let(:dbl) {double(:articles)}
describe 'GET index' do
it 'assigns @articles' do
get :index
allow(dbl).to receive(:articles).and_return article
expect(dbl.articles).to eql(article)
#expect_any_instance_of(Article).to receive(:save).and_return(true)
end
it 'renders the index template' do
get :index
allow(dbl).to receive(:articles)
expect(response).to render_template('index')
end
end
describe 'GET :new' do
it 'render new template' do
get :new
expect(response).to render_template(:new)
end
end
describe 'POST/create' do
it 'created a new article ' do
expect { post :create, article: art_params }.to change(Article, :count).by(1)
end
end
describe 'POST/create not' do
it 'did not create a new user' do
# expect(art_params).to receive(attributes_for :article).with(content:)
art_params = { article: attributes_for(:article, content: nil) }
post :create, art_params
expect(response).to render_template(:new)
end
end
describe 'GET/edit' do
it 'displays the edit template' do
get :edit, id: article.id
expect(response).to render_template(:edit)
end
end
describe 'POST/update' do
it 'displays the update template' do
post :update, id: article.id, article: attributes_for(:article)
expect(response).to redirect_to(article_path(article.id))
end
end
describe 'POST/DELETE' do
it 'destroys the article template' do
dbl = double()
article = create :article
expect { delete :destroy, id: article.id }.to change(Article, :count).by(-1)
end
end
en
d