我对 rspec、rails 和 ruby 很陌生。我现在正在学习它们。我发现我自己在我执行的每个单独测试中都放置了一个获取或发布请求,这不是很干。我是否需要不断发出这些请求才能使测试正常进行?还是我错过了一些基本的东西?
编辑:
对于我正在执行的每个测试,我都必须发出一个 get :page 样式的请求,以便 Controller 运行该请求。但是在测试同一个 Action 的各个方面时,我反复发出同一个请求,因此重复了代码。这不是 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
最佳答案
如果您对多个测试做同样的事情,您可以将它们移至 before block 。
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
如果您希望对所有测试仅调用一次公共(public)事物,则将 before :each
替换为 before :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
关于ruby-on-rails - Rspec,Rails,我是否需要为每个测试获取或发布请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13103604/