Rspec,Rails,我是否需要获取或发布每个测试的请求

时间:2012-10-27 19:49:33

标签: ruby-on-rails ruby testing rspec

我对rspec,rails和ruby都很新。我现在正在学习它们。我发现自己在我执行的每个测试中都提出了一个get或post请求,这个测试并不是很干。我是否需要继续发出这些测试请求才能工作?或者我错过了一些基本的东西?

编辑:

对于我正在执行的每个测试,我必须发出get:page样式请求,以便控制器运行请求。但是在测试相同操作的各个方面时,我会重复发出相同的请求,从而重复代码。这不是干的(不要重复自己)。

describe "Find Movies With Same Director" do
    it "should respond, and find the requested movie" do
      stubFind()
      id = "1"
      get :match_director, :id=>id
      response.code.should eq("200")
    end

    it "should search for movies with the same director" do
      id = "1"
      Movie.should_receive(:match_director).with(id)
      get :match_director, :id=>id
    end

    it "should pass all matching movies to view" do
      id = "1"
      Movie.should_receive(:match_director).with(id).and_return("")
      get :match_director, :id=>id
      assigns[:movies].should not_be nil
    end

    it "should pass a list of movies" do
      id = "1"
      Movie.stub(:match_director).and_return(stub_model(Movie))
      get :match_director, :id=>id

      assigns[:movies].should be_instance_of(Movie)
    end

  end

1 个答案:

答案 0 :(得分:2)

如果您正在为多个测试做同样的事情,可以将它们移到前一个块。

describe 'something' do
    it 'should do one thing' do
        common_thing
        specific_thing
    end

    it 'should do one thing' do
        common_thing
        specific_thing
    end
end

变为

describe 'something' do
    before :each do
        common_thing
    end

    it 'should do one thing' do
        specific_thing
    end

    it 'should do one thing' do
        specific_thing
    end
end

如果您希望所有测试只调用一次常见内容,则将before :each替换为before :all

编辑:看到你编辑后,我认为您可以将调用get :match_director, :id=>id放入方法中,然后使用它:

def call_match_director
    get :match_director, :id=>id
end

然后在一个地方添加params很容易。您还可以使用let construct:

将id放入变量中
let(:id) { "1" }

总而言之:

describe "Find Movies With Same Director" do
  let(:id) { "1" }

  def call_match_director
    get :match_director, :id=>id
  end

  it "should respond, and find the requested movie" do
    stubFind()
    call_match_director
    response.code.should eq("200")
  end

  it "should search for movies with the same director" do
    Movie.should_receive(:match_director).with(id)
    call_match_director
  end

  it "should pass all matching movies to view" do
    Movie.should_receive(:match_director).with(id).and_return("")
    call_match_director
    assigns[:movies].should not_be nil
  end

  it "should pass a list of movies" do
    Movie.stub(:match_director).and_return(stub_model(Movie))
    call_match_director
    assigns[:movies].should be_instance_of(Movie)
  end
end