0

有人可以帮我为以下代码创建模拟。我想通过以下名称在现有控制器中添加一个控制器方法,并希望将其行为测试到包含标题、导演、评级等作为表实例的电影类。不幸的是,我不熟悉在这里使用的 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
4

1 回答 1

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/

于 2013-11-12T18:20:02.203 回答