gpt4 book ai didi

ruby-on-rails - Ruby on Rails - RSpec - 重构 lambda 样式测试

转载 作者:数据小太阳 更新时间:2023-10-29 08:49:32 27 4
gpt4 key购买 nike

我很确定我可以让这个测试更干净,一直在搜索但无法破解它。测试通过,但我想重构。

describe "as an authenticated user that made the offer" do
before { log_in offering_user; }
specify { expect { delete :destroy, id: offer.id }.to change(Offer, :count).by(-1) }
describe "redirect and flash" do
before { delete :destroy, id: offer.id }
specify { response.should redirect_to item_path(offer.receiving_item) }
specify { flash[:success].should_not be_nil }
end
end

看看我如何不得不在规范中提出两次请求?它也迫使我使用另一个描述 block 。理想情况下,我可以只在第一个 before block 中发出请求,然后按照

it { should change(Offer, :count).by(-1) }

谁能指出我正确的方向?谢谢。

最佳答案

如果您不介意重构您的测试以使用 expect 语法 (recommended),并在同一个测试中测试多个条件,您可以执行以下操作:

describe "as an authenticated user that made the offer" do
let(:destroying_an_offer) { -> { delete :destroy, id: offer.id } }
before { log_in offering_user }

it "destroys offer" do
expect(destroying_an_offer).to change(Offer, :count).by(-1)
expect(response).to redirect_to(item_path(offer.receiving_item))
expect(flash[:success]).to_not be_nil
end
end

第一个 expect 将发出 delete 请求,其余的 expect 将在之后进行操作。

如果你想使用 should 语法,我认为你将无法避免多次发出请求,因此很难进一步重构它们眼镜。不过,作为一个值得深思的问题,如果您想具体说明应用程序受请求影响的不同方面,您甚至可以为每个规范更改 subject 以获得每个规范都集中在 it block 上:

describe "as an authenticated user that made the offer" do
before do
log_in offering_user
delete :destroy, id: offer.id
end

describe "behaviour" do
subject { response }
it { should redirect_to item_path(offer.receiving_item) }
end

describe "appearance" do
subject { flash[:success] }
it { should_not be_nil }
end

describe "result" do
subject { -> { delete :destroy, id: offer.id } }
it { should change(Offer, :count).by(-1) }
end
end

关于ruby-on-rails - Ruby on Rails - RSpec - 重构 lambda 样式测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16804547/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com