首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Ruby on Rails - RSpec -重构lambda风格的测试

Ruby on Rails - RSpec -重构lambda风格的测试
EN

Stack Overflow用户
提问于 2013-05-29 10:29:08
回答 2查看 283关注 0票数 2

我很确定我可以让这个测试变得更干净,我到处都在找,但就是不能破解它。测试通过了,但我想重构一下。

代码语言:javascript
运行
复制
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块中发出请求,并拥有类似以下内容的内容

代码语言:javascript
运行
复制
it { should change(Offer, :count).by(-1) }

有谁能给我指个方向吗?谢谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-05-29 20:35:22

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

代码语言:javascript
运行
复制
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块:

代码语言:javascript
运行
复制
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
票数 2
EN

Stack Overflow用户

发布于 2013-05-29 19:12:33

为了通过lambda表示法使用隐式主题,您可以执行以下操作:

代码语言:javascript
运行
复制
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

我还不知道如何让这个测试变得枯燥:)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16804547

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档