2

我对 rspec、rails 和 ruby​​ 很陌生。我现在正在学习它们。我发现自己在我执行的每个单独的测试中都提出了一个 get 或 post 请求,这不是很干燥。我是否需要继续发出这些请求才能使测试生效?还是我错过了一些基本的东西?

编辑:

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

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
4

1 回答 1

3

如果您对多个测试执行相同的操作,则可以将它们移动到 before 块。

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 :eachbefore :all.

编辑:看到你编辑后,我认为你可以把调用get :match_director, :id=>id放在一个方法中并使用它:

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

然后很容易将参数添加到一个地方的调用中。您还可以使用 let 构造将 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
于 2012-10-27T21:04:46.503 回答