rspec 测试嵌套 if 函数

发布于 2024-12-02 06:21:23 字数 344 浏览 0 评论 0原文

IM 对 rspec 测试非常陌生,需要一点帮助。

我正在测试我的时间表的控制器,并尝试测试这段代码。

if params[:user_id] == nil
      if current_user == nil
        redirect_to new_user_session_path
      else
        @user_id = current_user.id
      end
    else
      @user_id = params[:user_id]
    end

我不确定它是否值得测试,但似乎缺乏针对初学者的教程,所以我不知道。 提前致谢

IM very new to rspec testing and need alittle bit of help.

Im testing a controller for my timesheet and im trying to test this piece of code.

if params[:user_id] == nil
      if current_user == nil
        redirect_to new_user_session_path
      else
        @user_id = current_user.id
      end
    else
      @user_id = params[:user_id]
    end

im not sure if its even worth testing but it seems theres a lack of tutorials for the beginner out there, so i wouldnt know.
thanks in advance

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

行雁书 2024-12-09 06:21:23

您可以在rspec中使用describe语句和before(:each)来设置每个场景并测试它

describe "test the controller" do

    before(:each) do
        @user = Factory(:user)
    end

    describe "for non signed in users" do

        it "should redirect to sign in page" do
            get :action
            response.should redirect_to(new_user_session_path)
        end

    end

    describe "for signed in users" do

        before(:each) do
            sign_in(@user)
        end

        it "should be successful" do
            get :action
            response.should be_success
        end

    end

end

只需使用不同的describe语句并使用before(:each)设置每个测试就可以了。

You can do this in rspec using describe statements and before(:each) to setup each scenario and test it

describe "test the controller" do

    before(:each) do
        @user = Factory(:user)
    end

    describe "for non signed in users" do

        it "should redirect to sign in page" do
            get :action
            response.should redirect_to(new_user_session_path)
        end

    end

    describe "for signed in users" do

        before(:each) do
            sign_in(@user)
        end

        it "should be successful" do
            get :action
            response.should be_success
        end

    end

end

Just use different describe statements and setup each test with before(:each) and you should be fine.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文