【问题标题】:How can I refactoring test code for both JavaScript and HTML requests\responses?如何重构 JavaScript 和 HTML 请求\响应的测试代码?
【发布时间】:2011-09-30 22:46:32
【问题描述】:

我正在使用 Ruby on Rails 3.1.0 和 rspec-rails 2gem。由于我必须针对相同的控制器操作测试 HTML 和 JavaScript 请求,并且有时它们会通过呈现 不同 视图文件或行为 不同 来响应,因此我想重构一些代码.

通常,在我的控制器文件中,我有:

def create
  ...
  respond_to
    format.html
    format.js
  end
end

此时,为了同时测试 JS 和 HTML 请求\响应,在我的规范文件中,我有 两个不同的示例(每个示例一个示例):

context "POST create" do
  let(:user) { User.new }

  it "should correctly respond to a JS request" do
    xhr :post, :create
    ...
    session[:user].should be_nil
    flash[:notice].should be_nil
  end

  it "should correctly respond to a HTML request" do
    post :create
    ...
    session[:user].should be_nil
    flash[:notice].should be_nil
  end
end

我应该如何重构上面的代码?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 rspec rspec2


    【解决方案1】:

    你可以使用shared_examples_for

    context "POST create" do
      let(:user) { User.new }
    
      shared_examples_for "a succesfull request" do
        it("does not set the user")  { session[:user].should be_nil }
        it("does not set the flash") { flash[:notice].should be_nil }
      end
    
      context "with a js request" do
        before(:each) do
          xhr :post, :create
        end
    
        it_should_behave_like "a succesfull request"
      end
    
      context "with a HTML request" do
        before(:each) do
          post :create 
        end
    
        it_should_behave_like "a succesfull request"
      end
    end
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-20
      • 1970-01-01
      • 1970-01-01
      • 2019-09-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多