使用rails中的Rspec为控制器方法创建模拟

时间:2013-11-12 17:31:18

标签: unit-testing rspec ruby-on-rails-3.1 integration-testing bdd

有人可以帮助我为以下代码创建模拟。我想通过以下名称在现有控制器中添加控制器方法,并希望将其行为测试为包含标题,导演,评级等的电影类作为表格实例。不幸的是,我不熟悉这里使用的BDD命令。

describe MoviesController do
  describe "#find_same_director" do
    before :each do
      fake_movies = [mock('movie1'), mock('movie2')]        
    end
    context "with invalid attributes" do 
      it "flashes no such director message" do
        flash[:notice].should_not be_nil
      end 
      it "redirects to the index method" do 
        response.should redirect_to movies_path
      end 
    end
    context "with valid attributes" do
      it "calls model method to find all movies" do 
        movie = Movie.find_with_director, {:director => 'George Lucas'}
        get :show, id: @fake_movies 
        assigns(:movie).should eq(@fake_results) 
      end 
      it "renders the #find_same_director view" do 
        get :find_same_director, id: @fake_movies
        response.should render_template :find_same_director 
      end 
    end
  end
end

1 个答案:

答案 0 :(得分:1)

您是否注意到您尝试在不同的测试用例中测试不同的东西? (第一个上下文你​​没有执行动作“get:x”,你正在做的最后一个“get:show”

首先,你应该考虑你的代码的行为,所以,我可以想到两个上下文(在这种情况下你有什么样的情况):

  # with valid parameters(for e.g.: i should pass the right data, before this context i must create the data for the text).
  # with invalid parameters(for e.g: the parameters passed to the GET request should not be existent on the system).

然后你应该考虑当这个环境活跃时会发生什么。

  context "with valid parameters" do 
    it "should return the other movies of the same director, and assign it to the @movies"
    it "should render the template of the #find_same_director page"
  end 
  context "with invalid parameters" do
    it "should redirect to the movies_path"
    it "should put a flash message that the director is invalid"
  end

在考虑测试用例之后,你必须考虑如何实现它们,我会给你一个提示:

it "should return the other movies of the same director, and assign it to the @movies" do
  # THINKING ABOUT BDD HERE YOU SHOULD THINK OF THIS CODE SECTIONS AS FOLLOW:
  # GIVEN ( OR THE CONDITIONS FOR THE ACTION HAPPEN)
  @director = Director.new
  movies = [Movie.new, Movie.new]
  @director.movies = movies
  # HERE ILL FIX THE VALUES SO I CAN USE IT ON MY EXPECTATIONS
  Director.stub!(:find).with(@director_id).and_return(@director)
  # WHEN, THE ACTION HAPPENED
  get :find_same_director, :id => @director_id
  # THEN THE EXPECTATIONS THAT SHOULD BE MATCHED
  assigns(:movies).should == @director.movies
end

为了获得更真实的测试体验,我建议您观看截屏视频:http://destroyallsoftware.com/