我很确定我可以让这个测试变得更干净,我到处都在找,但就是不能破解它。测试通过了,但我想重构一下。
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看到我如何在规范中提出两次请求了吗?这也迫使我使用另一个describe代码块。理想情况下,我可以只在第一个before块中发出请求,并拥有类似以下内容的内容
it { should change(Offer, :count).by(-1) }有谁能给我指个方向吗?谢谢。
发布于 2013-05-29 20:35:22
如果您不介意重构测试以使用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块:
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发布于 2013-05-29 19:12:33
为了通过lambda表示法使用隐式主题,您可以执行以下操作:
describe "as an authenticated user that made the offer" do
  before { log_in offering_user }
  subject { -> { delete :destroy, id: offer.id } }
  it { should change {Offer.count}.by(-1) }
end我还不知道如何让这个测试变得枯燥:)
https://stackoverflow.com/questions/16804547
复制相似问题