如何使用相同的rpsec测试用例来测试不同的站点

时间:2016-04-08 02:50:45

标签: rspec

我想使用相同的rpsec测试用例来测试不同的网站, 例如,我可以一次测试所有网站,而且我也可以一次测试其中一个网站。 你介意给我一些建议吗?我怎么能以一种简单的方式做到这一点。

我宝石安装rspec,而不是rspec-rails。 这是我的代码

require 'spec_helper'
require 'net/http'
require 'json'
require 'uri'


describe 'mywebsite1' do
  uri = URI.parse('http://mywebsite1/')
  initheader = {'Content-Type' =>'application/json'}
  req = Net::HTTP::Post.new(uri, initheader)

describe 'common_test' do
  payload = JSON.parse(open("file.json").read)
  req.body = payload.to_json
  context 'case1' do
  res = Net::HTTP.start(uri.host, uri.port) do |http|
    http.request(req)
  end
  result = JSON.parse(res.body)
  it "should response with the code 201" do
    expect("#{res.code}").to eq '201'
  end
  specify "status is Ready" do
    expect(result['item']['status']).to eq 'Ready'
  end
  specify "type is All" do
    expect(result['item']['type']).to eq 'All'
  end
end
    context 'case2' do
    ...
    end
  end  
end

1 个答案:

答案 0 :(得分:3)

您可以使用shared_examples_for重复使用不同规范之间的一组示例,例如

shared_examples_for 'a website' do
  context 'case1' do
    let(:req) {
      Net::HTTP::Post.new(uri, {'Content-Type' => 'application/json'})
    }

    let(:res) {
      Net::HTTP.start(uri.host, uri.port) do |http|
        http.request(req)
      end
    }

    it 'should respond with 201' do
      expect(res.code.to_i).to eq(201)
    end
  end
end

然后,当您想使用共享示例时,使用it_should_behave_like并传递共享示例的名称,例如

describe 'my website' do
  it_should_behave_like 'a website' do
    let(:uri) { URI.parse('http://mywebsite') }
  end
end

describe 'a different website' do
  it_should_behave_like 'a website' do
    let(:uri) { URI.parse('http://anotherwebsite') }
  end
end

您可以在the docs

查看更多详情
相关问题