代码之家  ›  专栏  ›  技术社区  ›  AlbertMunichMar

已提取到宝石。使用gem“rails controller testing”。创业板还有别的选择吗?

  •  0
  • AlbertMunichMar  · 技术社区  · 7 年前

    Task.all ).

    RSpec.describe TeamsController do
      describe "GET index" do
        it "assigns @teams" do
          team = Team.create
          get :index
          expect(assigns(:teams)).to eq([team])
        end
    
        it "renders the index template" do
          get :index
          expect(response).to render_template("index")
        end
      end
    end
    

    这个 assigns 方法移到gem文件“rails controller testing”中。 我有两个问题:

    1-我怎样才能达到 expect(assigns(:teams)).to eq([team]) . 我想我是在问,如何检查在索引操作中是否有一个实例变量具有值 [team]

    spec/models/tasks_controller.rb index 实例变量@teams是否包含我想要的内容?

    1 回复  |  直到 7 年前
        1
  •  4
  •   max Mike Williams    5 年前

    整个想法是,与其戳控制器内部并测试其内部变量有缺陷,不如通过测试输出来测试控制器。

    在RSpec中,您可以通过请求和特性规范来实现这一点。

    # config/specs/features/teams_spec.html
    RSpec.feature 'Teams' do
      scenario 'when a user views the teams' do
        Team.create(name: 'Team Rocket')
        visit '/teams'
        expect(page).to have_content 'Team Rocket'
      end
    end 
    
    # config/specs/requests/teams_spec.html
    RSpec.describe 'Teams', type: :request do
      describe 'GET /teams.json' do
        it "includes the team" do
          team = Team.create(name: 'Team Rocket')
          get teams_path(format: :json) 
          expect(parsed_response.first['name']).to eq 'Team Rocket'
        end  
      end
      describe 'GET /teams' do
        it "includes the team" do
          team = Team.create(name: 'Team Rocket')
          get teams_path
          expect(page).to have_content 'Team Rocket'
        end  
      end
    end
    

    关键的区别在于,特性规格通过驱动浏览器模拟器从用户故事视角测试应用程序,而请求规格更轻,您只需根据原始响应进行测试。

    1-我如何实现与预期(分配(:团队))相同的目标 情商([团队])。我想我是在问,我该如何检查我是否有一个实例

    只是测试反应,饼干等,但我很困惑,因为在欣赏你 可以测试实例变量。我该不该在那里测试?如果没有,

    3-备选方案:既然TeamsController是一个普通类,我应该 实例变量@teams包含我想要的内容?

    MyController.new ,这就是为什么控制器测试有所有的存根。